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.
两种方法,做出来结果都是4ms。第一种是打表,第二种是直接算C(m+n-2,n-1)。但第二种的复杂度从时间和空间上来讲都更优一些吧。
方法一:如果用table[m][n]表示结果,那么table[m][n]=table[m-1][n]+table[m][n-1]是很容易想到的。用递归的方法也小实验了一下,递归树太大,无可争议的TLE。所以想到用打表的方法来做。时间和空间复杂度均为O(m*n)。
class Solution {
public:
int table[101][101];
int uniquePaths(int m, int n) {
for(int i=1;i<=m;++i){
for(int j=1;j<=n;++j){
if(i==1||j==1){
table[i][j] = 1;
}
else{
table[i][j] = table[i-1][j]+table[i][j-1];
}
}
}
return table[m][n];
}
};
方法二:走的步数一共是m+n-2次,从里面选出m-1次向下的和n-1次向上的就行了。所以C(m+n-2,n-1)就可以。麻烦的是算起来容易溢出。之前编程的时候遇到过类似的问题,找到了一个可以大概避免溢出的小办法。就是一边乘一边除。时间复杂度降低到O(m+n),空间复杂度降低到O(1)
class Solution {
public:
int uniquePaths(int m, int n) {
//C(m+n-2,n-1)
int max = m>n? m-1 : n-1;
int min = m+n-2-max;
unsigned long long res = 1;
int little=2;
for(int k=max+1;k<=m+n-2;++k){
res*=k;
while(res%little==0&&little<=min){
res/=little;
little++;
}
}
return (int)res;
}
};