题目描述:
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?
Note: m and n will be at most 100.
题目分析:
我们可以用count[i][j]
来表示到第i
行第j
列的空格上一共有多少种走法,经过分析,会有下式关系:
count[i][j] = count[i - 1][j] + count[j][i - 1]
有了递推关系,就可以很容易地实现本题的解了:
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> count(m,vector<int>(n,1));
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
count[i][j] = count[i - 1][j] + count[i][j - 1];
}
}
return count[m - 1][n - 1];
}
};
上面的解法时间复杂度为 O(mn) ,空间复杂度为 O(mn) 。但其实上面的解法只涉及到两行,因此,可以简化上述算法的空间复杂度至 O(n) :
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> count1(n, 1);
vector<int> count2(n, 1);
for(int i = 1; i < m; i++){
if(i % 2){
add(count2, count1);
}else{
add(count1, count2);
}
}
return max(count1[n - 1], count2[n - 1]);
}
void add(vector<int>& counta, vector<int>& countb){
for(int i = 1; i < counta.size(); i++){
counta[i] = counta[i - 1] + countb[i];
}
}
};
再仔细查看上面代码,可以注意到实际上可以使用一个数组来完成任务,从而更简化代码:
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> count(n, 1);
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
count[j] = count[j - 1] + count[j];
}
}
return count[n - 1];
}
};