斐波那契数列三种方法计算,光棍节快乐
Posted Roam-G
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了斐波那契数列三种方法计算,光棍节快乐相关的知识,希望对你有一定的参考价值。
//斐波那契数列三种方法计算
//Fibnacci(0)=0
//Fibnacci(1)=1
//Fibnacci(n)=Fibnacci(n-1)+Fibnacci(n-2) [n>1]
//1.递归计算
//斐波那契数列三种方法计算
//Fibnacci(0)=0
//Fibnacci(1)=1
//Fibnacci(n)=Fibnacci(n-1)+Fibnacci(n-2) [n>1]
//1.递归计算
long Fibnacci(long n) {
if (n <= 1) return n;
return Fibnacci(n - 1) + Fibnacci(n - 2);
};
//2.利用栈的非递归
struct Node {
long n;//记忆走过的 n
int tag;//区分 左右
};
long Fibnacci(long n) {
Stack<T> S;
Node* w;
long sum = 0;
do {
while (n > 1) {
w->n = n;
w->tag = 1;
S.push(w);
n--;
}
sum = sum + n;
while (S.IsEmpty() == false) {
S.Pop(w);
if (w->tag == 1) {
w->tag == 2;S.Push(w);n = w->n - 2;
break;
}
}
} while (S.IsEmpty() == false);
return sum;
};
// 3.迭代
long Fibnacci(long n) {
if (n <= 1)return n;
long two = 0, one = 1, sum;
for (int i = 2;i <= n;i++) {
sum = two + one;
two = one;
one = sum;
}
return sum;
};
以上是关于斐波那契数列三种方法计算,光棍节快乐的主要内容,如果未能解决你的问题,请参考以下文章