题目:
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:递归
终点的路径数= 所有能达到终点的点的路径数之和,即为:路径[m][n] = 路径[m-1][n] + 路径[m][n-1]
依次递归,直到start点(0,0)
代码:
public static int uniquePaths(int m, int n) { if(n == 1 && m==1){ //初始的位置 return 1; } else if(n == 1 && m>1){ return uniquePaths(1,m-1); } else if(n >1 && m==1){ return uniquePaths(n-1,1); } else{ return uniquePaths(n-1,m)+uniquePaths(n,m-1); } }
结果在m=17 n=23的时候超时了。所以意识到题目的限制条件是需要速度!
思路2:动态规划
某一个点的路径数= 所有能达到该点的点的路径数之和,即为:路径[m][n] = 路径[m-1][n] + 路径[m][n-1]
与递归不同的是,递归是从大往小算,动态规划是从小往大算
代码如下:
public static int uniquePaths(int m, int n) { int[][] arrResult = new int[m][n]; for(int i = 0;i<m;i++){ for(int j = 0;j<n;j++){ if(i == 0 && j== 0){ arrResult[0][0] = 1; } else if(i == 1 && j== 0){ arrResult[1][0] = 1; }else if(i == 0 && j== 1){ arrResult[0][1] = 1; } //以上是填充基础值 else{ int row = 0; int column = 0; if(i> 0 ){ row = arrResult[i-1][j]; } if(j> 0 ){ column = arrResult[i][j-1]; } arrResult[i][j] = row + column; } } } return arrResult[m-1][n-1]; }