[LeetCode]62 不同的路径总数
2016-02-28 13:31
495 查看
Unique Paths(不同的路径总数)
【难度:Medium】A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
位于m*n矩阵的一个机器人只能向下或向右移动,求其从Start移动到Finish不同的走法总数。
解题思路
这是一道典型的动态规划问题,使用一个二维数组ans记忆到达每一点可行的走法总数。首先将左边界点和上边界点初始化为1,因为机器人起始与(0,0),左边界点和上边界点的走法只有1种。接下来的每一点(x,y),可以由(x-1,y)向右走或是(x,y-1)向下走来到达,因此在(x,y)这一点可到达的方法有ans[x-1][y]+ans[x][y-1]种,到达终点的方法则是ans最后一个点的数据。c++代码如下
class Solution { public: int uniquePaths(int m, int n) { if (m == 0 || n == 0) { return 0; } vector<vector<int>> path(m,vector<int>(n,0)); for (int i = 0; i < m; i++) path[i][0] = 1; for (int i = 0; i < n; i++) path[0][i] = 1; for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { path[i][j] = path[i-1][j] + path[i][j-1]; } } return path[m-1][n-1]; } };
相关文章推荐
- 线性插值(linear interpolation)
- JSP—九大隐式对象之pageContext
- 关于用struts2框架中iframe对应的jsp页面的不到action的值的问题
- 其他IO流
- 认识数据仓库建设意义
- 从Eclipse迁移到Android Studio
- a标签点击后的虚线框
- JAVA通过ftp远程获取文件并压缩
- Leetcode ☞ 319. Bulb Switcher ☆ brain teaser
- Oracle数据库SQL优化
- 2016/02/28 codes
- 数据的离散化
- 有一种设计风格叫RESTful
- 成员指针运算符 .* 和 ->*
- How computer work?
- The Dominant Color (20)
- zstu 1024 Wooden Sticks
- 智能
- 最新首发Eclipse+CDT+android-ndk写纯c++安卓应用(附openGL Es)
- 关于sort的使用