实现您想要的系列的简单递归可以是:
public class FibRecursion{
private static BigInteger[] fval;
public static void main(String[] args) {
int index = 10;
fval = new BigInteger[index];
fib(0,1,0,index);
System.out.println(Arrays.toString(fval));
}
public static void fib(long a, long b, int index, int endIndex ) {
if (index >= endIndex) {
return ;
}
fval[index] = BigInteger.valueOf(a).add(BigInteger.valueOf(b));
index++;
fib(b, a+b, index , endIndex);
}
}
为了避免堆栈限制,您可以限制递归深度,并以几个“段”进行复活.这是一系列50个元素的示例,其深度限制为10(RECURRSION_DEPTH = 10):
public class FibRecursion{
private static BigInteger[] fval;
//limit of the recursion depth. valid values are >=2
private final static int RECURRSION_DEPTH = 10;
public static void main(String[] args) {
int index = 50;
fval = new BigInteger[index];
BigInteger aValue = BigInteger.valueOf(0);
BigInteger bValue = BigInteger.valueOf(1);
int startIndex = 0;
int endIndex = RECURRSION_DEPTH;
while (endIndex > startIndex) {
fib(aValue,bValue,startIndex,endIndex);
aValue = fval[endIndex-2];
bValue = fval[endIndex-1];
startIndex = endIndex;
endIndex = Math.min(endIndex + RECURRSION_DEPTH, index);
}
System.out.println(Arrays.toString(fval));
}
//use BigInteger to avoid integer max value limitation
public static void fib(BigInteger a, BigInteger b, int index, int endIndex ) {
if (index >= endIndex) {
return ;
}
fval[index] = a.add(b);
index++;
fib(b, a.add(b), index , endIndex);
}
}
当然,这还有其他限制,与堆栈大小无关.