原题如下(链接:https://leetcode.com/problems/unique-paths/):
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?
解题思路:可以类比到青蛙跳台阶的题,其实只要找到一个递推公式就可以了,F(m,n) = F(m-1, n) + F(m, n-1);
递归求解的话会超时,但是比较容易理解,代码如下:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1)
return 0;
if(n == 1 || m == 1)
return 1;
else
return uniquePaths(m-1, n) + uniquePaths(m, n-1);
}
把递归改成循环可以顺利AC,C++代码如下:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1)
return 0;
int **mn = new int*[m];
for(int i=0; i<m; i++){
mn[i] = new int[n];
}
for(int i=0; i<m; i++){
mn[i][0] = 1;
}
for(int i=0; i<n; i++){
mn[0][i] = 1;
}
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
mn[i][j] = mn[i][j-1] + mn[i-1][j];
}
}
return mn[m-1][n-1];
}