个人总结:1,代码总要动手写写,
2,由于老师上课要求我们会递归与非递归,所以fibnacci我都试试
之后会尝试二叉树递归与非递归两个方法
// Chapter3_fibnacci.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<stack>
using namespace std;
long fib(long n) {
if (n <= 1) return n;
else {
return fib(n - 1) + fib(n - 2);
}
}//递归
//********************************************************
struct Node {
long n;
int tag;
};
long fib2(long n) {
stack<Node> s;
Node* w=new Node();
long sum = 0;
do {
while (n > 1) {
w->n = n;
w->tag = 1;
s.push(*w);
n--;
}
sum = sum + n;
while (!s.empty()) {
w = &s.top();
s.pop();
if (w->tag == 1) {
w->tag = 2;
s.push(*w);
n = w->n - 2;
break;
}
}
} while (!s.empty());
return sum;
};//非递归1
//********************************************************
//画图递归理解
long fib3(int n) {
if (n <= 1) return n;//f(0)或f(1)的情况
long twoback = 0, oneback = 1, current;//n>=2的情况
for (int i = 2; i <= n; i++)
{
current = twoback + oneback;//计算f(n)=f(n-2)+f(n-1)
twoback = oneback;//计算f(n-1),下趟的f(n-2)
oneback = current;//计算f(n),下趟的f(n-1)
}
return current;
}
//********************************************************
int main() {
long ans1 = fib(10);
cout << "ans1:" << ans1 << endl;
cout << "***********************" << endl;
ans1 = fib2(10);
cout << "ans2:" << ans1 << endl;
cout << "***********************" << endl;
ans1 = fib3(10);
cout << "ans3:" << ans1 << endl;
return 0;
}