题目链接: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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
解题思路:
动态规划方法:用一个大小为m * n的二维数组Path代表整个diagram,其中Path[m-1][n-1] 表示从Start到Finish的unique paths数量。 那么到达[m-1][n-1]的上一个位置只可能是[m-2][n-1]或者[m-1][n-2]。 因此可以得到最关键的信息: Path[m-1][n-1] = Path[m-2][n-1] + Path[m-1][n-2]. 以及初始化时的 Path[i][0] = Path[0][j] = 1.
代码实现:
使用递归(未通过LeetCode测试,出现Time Limit Exceeded错误):
public class Solution {
public int uniquePaths(int m, int n) {
if ((m == 1 )||(n == 1)){
return 1;
}else{
return uniquePaths(m-1, n) + uniquePaths(m, n-1);
}
}
}
不使用递归(通过LeetCode测试):
public class Solution {
public int uniquePaths(int m, int n) {
int [][] array = new int[m][n];
for (int i=0;i
原因分析:
递归方法和非递归方法的计算结果是一致的,但是递归方法使用的时间远远大于非递归方法,所以没有通过LeetCode测试,下面它们运行时间的比较:
diagram大小: 非递归时间 | 递归时间
[15][0]: 0ms | 0ms
[15][1]: 0ms | 0ms
[15][2]: 0ms | 0ms
[15][3]: 0ms | 0ms
[15][4]: 0ms | 0ms
[15][5]: 0ms | 0ms
[15][6]: 0ms | 0ms
[15][7]: 0ms | 0ms
[15][8]: 0ms | 0ms
[15][9]: 0ms | 19ms
[15][10]: 0ms | 29ms
[15][11]: 0ms | 52ms
[15][12]: 0ms | 157ms
[15][13]: 0ms | 250ms
[15][14]: 0ms | 696ms
[15][15]: 0ms | 1077ms
可以看出,随着diagram增大,时间差距越来越大。