题目描述:
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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
解题思路:
这题最先想到的是递归,但递归耗时太久了无法通过。于是改用动态规划的方法,思路与递归类似。不同的是:递归是从终点开始寻找路径,然后往前叠加;而动态规划是从起点开始寻找,往后叠加。
我的代码:
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 vector<vector<int>> ret(m, vector<int>(n, 1)); 5 for(int i = 1; i < m; i++){ 6 for(int j = 1; j < n; j++){ 7 ret[i][j] = ret[i-1][j]+ret[i][j-1]; 8 } 9 } 10 return ret[m-1][n-1]; 11 } 12 };
他人代码:
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 //参考了LeetCode上的优质解答,思路也是动态规划,把无用的数组去掉了 5 vector<int> ret(n, 1); 6 for(int i = 1; i < m; i++){ 7 for(int j = 1; j < n; j++){ 8 ret[j] += ret[j-1]; 9 } 10 } 11 return ret[n-1]; 12 } 13 };