题解 | #斐波那契数列#
斐波那契数列
http://www.nowcoder.com/practice/aa8ffe28ec7c4050b2aa8bc9d26710e9
F[0]=0,F[1]=1
F[n]=F[n-1]+Fn-2
法一:递归
function fibonacci(n) { //1.递归 if(n==0) return 0 else if(n==1) return 1 else return fibonacci(n-1)+fibonacci(n-2) }
法二:循环
//2.循环 let n1=0 let n2=1 let res if(n==0) return n1 if(n==1) return n2 while(n>=2){ res=n1+n2; n1=n2; n2=res n-- } return res
法二用解构赋值
let n1=0 let n2=1 if(n==0) return 0 if(n==1) return 1 while(n>=2){ [n1,n2]=[n2,n1+n2] n-- } return n2