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.我的直观想法(递归)
当时的直观想法是,当走到最后一格,将总数num加一。
class Solution { public: void uniquePath(int begin, int end, int m, int n, double& num){ if(begin==m-1 && end == n-1){ num++; return; }else if(begin == m-1 || end == n-1){ if(begin == m-1) uniquePath(m-1, end+1, m, n, num); if(end == n-1) uniquePath(begin+1, n-1, m, n, num); }else{ uniquePath(begin, end+1, m, n, num); uniquePath(begin+1, end, m, n, num); } return; } int uniquePaths(int m, int n) { double num = 0; int begin = 0, end = 0; if(m == 1 || n == 1) return 1; uniquePath(begin,end,m,n,num); return num; } };
3x3->6
3x4->10
5x3->15
2.动态规划
提交后发现会超时,就知道这种方法不对,需要动态规划。那么直接想法是,找一格m*n的格子,每个格子存储着从开始位置到该位置的路径。该位置的路径值就是f[i,j] = f[i-1,j]+f[i,j-1]. 然后初始化时,[0,0~n-1]及[0~m-1,n]都是1,因为只有一条路径到这些位置。
然后再用滚动数组,只用一列,代替m*n的矩阵,就能降低空间复杂度。
class Solution { public: int uniquePaths(int m, int n) { double num = 0; int begin = 0, end = 0; if(m == 1 || n == 1) return 1; vector<int>vec(n,1); while(--m){ for(int i = 1; i < n; i++){ vec[i] += vec[i-1]; } } return vec[n-1]; } };