我正在学习java,正在练习数组。我决定生成一个斐波那契数列作为实验,并且不禁想到可能有更简单的方法来生成这个系列(使用数组和循环)。有没有比这更好的显示斐波那契数列的方法?
有什么想法?
//Generate a Fibonacci series
public class Array {
public static void main(String[] args) {
// An array to store the values
int[] intArray = new int[20];
// starting values for the sequence
intArray[0] = 0;
intArray[1] = 1;
//display the first values
System.out.println("array["+(0)+"] = "+intArray[0]);
System.out.println("array["+(1)+"] = "+intArray[1]);
//generate the fibonnacci progression with a loop
for (int count=2;count<intArray.length;count++){
intArray[count] = intArray[(count-1)]+intArray[(count-2)];
System.out.println("array["+(count)+"] = "+intArray[count]);
}
}
我总是尽管斐波那契是,当不使用递归的解决方案很好的例子。因为最终汇总的唯一数字在递归尾部为1,因此运行时间与结果成正比。 – devconsole 2013-03-16 00:36:26
动态编程解决方案绝对没有错。 – Makoto 2013-03-16 00:38:07
简单的迭代解决方案也没有问题,但递归解决方案是优雅的,效率不高,但问题在于优雅。 – 2013-03-16 00:40:56