【发布时间】:2016-06-27 04:39:46
【问题描述】:
我正在做一个 leetcode 问题。
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?
所以我首先尝试了这个实现并得到了“超过运行时间”(我忘记了确切的术语,但这意味着实现很慢)。所以我将其更改为版本 2,它使用数组来保存结果。老实说,我不知道递归在内部是如何工作的,以及为什么这两种实现具有不同的效率。
版本 1(慢):
class Solution {
// int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}
}
};
version2(更快):
class Solution {
int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
if (res[m-1][n]==0) res[m-1][n] = uniquePaths(m-1,n);
if (res[m][n-1]==0) res[m][n-1] = uniquePaths(m,n-1);
return res[m-1][n] + res[m][n-1];
}
}
};
【问题讨论】:
-
一眼看去,第二个似乎就是en.wikipedia.org/wiki/Dynamic_programming。它不会计算两次结果。在两个方法的开头加上
System.out.println("Call with "+m+" and "+n),用小输入试试。你会看到区别。另见stackoverflow.com/a/25665931/3182664 -
它使用记忆化
标签: recursion