更新2014年10月23日:我认为递归函数基本上是一个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));
}
}