【发布时间】:2014-12-18 16:55:32
【问题描述】:
更新 10/23/2014:我认为递归函数基本上是一个 void 函数,所以返回后不需要更多工作,它应该相当于尾递归版本。它不应该导致堆栈溢出。我实际上也尝试了尾递归非空返回类型,它仍然导致堆栈溢出错误。我想即使它是尾递归的,它仍然取决于编译器解释器如何实现它。
相同代码的for循环版本不会导致堆栈溢出错误。但是下面的代码(递归版本)可以。本质上他们应该做同样的事情。异常错误出现在循环 7000 (i=7000) 附近。
我很好奇为什么递归版本会导致错误,而 for 循环版本不会。我有些怀疑,但不确定。
//recursive version, overflow
public class Solution {
int n, low = -1, profit = 0;
int[] a;
public int maxProfit(int[] prices) {
n = prices.length;
if (n == 0 || n == 1)
return 0;
a = prices;
maxProfit(1);
return profit;
}
public void maxProfit(int i) {
if (i == n - 1) {
if (low != -1 && a[i - 1] <= a[i])
profit += a[i] - low;
return;
}
if (a[i - 1] < a[i] && low == -1) {
low = a[i - 1];
}
if (a[i - 1] > a[i] && low != -1) {
profit += a[i - 1] - low;
low = -1;
}
//System.out.print(i+",");
maxProfit(i + 1);
}
public static void main(String[] args) {
Solution sl = new Solution();
// int[] a = { 1, 9, 6, 9, 1, 7, 1, 1, 5, 9, 9, 9 };
// int[] a = { 4, 4 };
// int[] a = { 3, 2 };
// int[] a = { 1, 2, 3, 4, 3 };
// int[] a = { 3, 2, 1, 0, 4, 5, 6, 7, 10, 4, 9, 7 };
int[] a = new int[100001];
for (int i = 0; i < 100001; i++) {
a[i] = 100000 - i;
}
System.out.println();
System.out.println(sl.maxProfit(a));
}
}
【问题讨论】:
-
这可能与递归版本有关,希望能够拥有 100000 帧深的调用堆栈...
-
当你的基本情况没有被命中时,递归函数往往会导致 StackOverflowError,使堆栈展开......这可能是因为搞砸了基本情况逻辑,而不是朝着基本情况移动,或试图递归太深
标签: java stack-overflow