【发布时间】:2015-10-11 17:56:27
【问题描述】:
我正在尝试将以下算法从递归更改为迭代,但在这样做时遇到了问题。 (书:“破解编码面试。”)
问题:“一个孩子正在跑上 n 步的楼梯,一次可以跳 1、2 或 3 步。实现一种方法来计算孩子可以跑多少次楼梯。”
书的答案(递归):
public static int countWays(int n, int[] map) {
if (n < 0)
return 0;
if (n == 0)
return 1;
if (map[n] > -1)
return map[n];
map[n] = countWays(n - 1, map) + countWays(n - 2, map) + countWays(n - 3, map);
return map[n];
}
我的答案(迭代):
public static int countWays(int n, int[] map) {
for (int i = 1; i <= n; i++) {
//Problem with writing it this way: index could be negative
map[i] = map[i - 1] + map[i - 2] + map[i - 3];
}
return map[n];
}
我给定答案的一个问题是“map[i - 1] + map[i - 2] + map[i - 3]”这行可能会导致负索引,这会引发错误。
我的代码可能还有其他问题。
有人可以帮忙写这个吗?
【问题讨论】:
-
对于 Python 中的迭代 O(n) 和 O(log(n)) 解决方案,请参阅this answer。
标签: java algorithm debugging recursion iteration