recursion - 尝试将递归用于斐波那契数列(JAVA)时出现越界异常
问题描述
如果有人向我解释这个问题的解决方案,我也将不胜感激,因为我认为我的逻辑不正确。
public class FibanacciSequence {
public static void main(String[] args)
{
fibSeq(5,5);
}
public static int[] fibSeq(int startNum, int iterations)
{
int[] arr = new int[iterations];
int nextNum = 0;
arr[0] = startNum;
if(iterations == 0)
{
return arr;
}
else
{
arr[nextNum] = startNum+startNum;
arr[nextNum+1] = nextNum + startNum;
arr=fibSeq(nextNum,iterations-1);
}
return arr;
}
}
解决方案
当迭代 <= 0 时,您的代码将失败
arr[0] = startNum;
当 0 < 迭代次数 <= nextNum + 1 时,您的代码将失败
arr[nextNum] = startNum + startNum;
arr[nextNum + 1] = nextNum + startNum;
在编码之前,您可能应该在纸上更详细地制定您的计划。
推荐阅读
- c# - Flurl 的 PostUrlEncodedAsync 忽略 JsonProperty 名称
- python - 未排序的段 argmax 解决方法 tensorflow
- excel - 我想检查数据表上是否存在时间重叠
- javascript - 将防伪令牌附加到 XMLHttpRequest
- javascript - 如何在像uploadify 这样的dropzone 中添加数据?
- java - 我正在编写一个 NewDate 类并在 TestNewDate 类中使用它。我认为我的验证日期方法有问题
- reactjs - eslint JSX 返回错误“表达式预期”
- c - 如何在 c 中执行有符号右移(>>)?
- r - 如何在同一列中导入具有混合日期类型的 xlsx?
- html - 如何在 html 输入文本中添加多个模式