Question:
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.
此题首先想到数学方法即排列组合,如示例所示,可以将横着走每部之间可以插入竖着走的排列组合,首先3*7的矩阵,竖着走即可向下走的地方为7处,每处可能走0-2步,情况分为:
1、连着走两步即 总共有7种
2、先走一步再走一步,计算方法为选向下走时的的y坐标 即6(在y=1时向下走) +5+。。。+1 = 21
共28种
但当向下走的总步数多时情况复杂多比如3步数分为1,2;2,1;3;1,1,1;因此考虑递归方法
第一种递归为将子递归分为从第二行开始为起点,即3*7矩阵的话从第二行开始共有7个起点(7乘以2*7矩阵的步数)以此类推
代码为:
int uniquePaths(int m, int n) {
if(m==1 || n==1) return 1;
int s = 0;
while(n--)
s += uniquePaths(m-1,n+1) ;
return s;
}
第二种递归为:因每个起点只有两个初始出发点即(2,7)和(3,6)
int uniquePaths(int m, int n) {
if(m==1 || n==1) return 1;
return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}
第二种更为简洁,但两份代码均未通过,当矩阵大于15后运算时间大于1s,因此声明静态局部变量,将已经运算后的结果储存避免多次计算:
int uniquePaths(int m, int n) {
static int a[100][100] = {0};
if(m==1 || n==1) return 1;
if(a[m-1][n-1] != 0) return a[m-1][n-1];
a[m-1][n-1] = uniquePaths(m-1,n) + uniquePaths(m,n-1);
return a[m-1][n-1];
}