仅作学习记录用,求解斐波那契数列的三种方法,其中第二种相对较难理解
#include <stack>
using namespace std;
class Solutions {
public:
long Fibnacci1(long n); //递归
long Fibnacci2(long n); //利用栈
long Fibnacci3(long n); //迭代
};
long Solutions::Fibnacci1(long n) {
if (n <= 1)
return n;
else
return Fibnacci1(n - 1) + Fibnacci1(n - 2);
}
struct Node {
long n;
int tag;
};
long Solutions::Fibnacci2(long n) {
stack<Node*> st;
Node* p=NULL;
long sum = 0;
do {
while (n > 1) {
p = new Node;
p->n = n; p->tag = 1;
st.push(p);
n--;
}
sum += n;
while (!st.empty()){
p = st.top();
st.pop();
if (p->tag == 1) {
p->tag = 2;
st.push(p);
n = p->n - 2;break;
}
}
} while (!st.empty());
return sum;
}
long Solutions::Fibnacci3(long n) {
long fb0 = 0, fb1 = 1;
long temp, count = n - 1;
while (count>0)
{
temp = fb1;
fb1 = fb1 + fb0;
fb0 = temp;
count--;
}
if (n <= 1)
return n;
else
return fb1;
}