递归

来源:互联网 发布:淘宝原创服装品牌 编辑:程序博客网 时间:2024/06/05 14:51

斐波那契数列

#include "stdafx.h"#include<iostream>  using namespace std;int f(int index){    if (index==1||index==2){        return 1; //递归程序的出口    }    else{        return f(index-1)+f(index-2);    }}int _tmain(int argc, _TCHAR* argv[]){    cout<<f(4);    return 0;}

enter description here

求阶乘

#include "stdafx.h"#include<iostream>  using namespace std;int f(int index,int sum){    if (index==1){        return sum; //递归程序的出口    }    else{        sum = sum*(--index);        return f(index,sum);    }}int _tmain(int argc, _TCHAR* argv[]){    cout<<f(4,4);    return 0;}
#include "stdafx.h"#include<iostream>  using namespace std;int f(int index){    if (index==1){        return 1; //递归程序的出口    }    else{        return f(index-1)*index;    }}int _tmain(int argc, _TCHAR* argv[]){    cout<<f(4);    return 0;}

enter description here

汉诺塔问题

中间过程:

enter description here
分为三步骤:

(前)“将那坨N-1个盘子从A针移动到B针”
(中)“移动最大盘子”
(后)“将坨N-1个盘子从B针移动到C针”。

(前)与(后)操作道理是相似的。不去管那个最大盘子,(前)是以C针为中转站,(后)是以A针为中转站。

Hn=Hn-1x 2 + 1.
F(n) = 2 F(n-1) + 1,F(1) = 1

#include "stdafx.h"#include<iostream>  using namespace std;void f(int index,int a,int b,int c){    if (index==1){        cout << "from" << a << " to " << c<<endl; //最后将底盘从a移动到c    }    else{        f(index - 1, a, c, b);//将n-1个盘子从a移动到b        cout << "from" << a << " to " << c << endl;  //将底盘从a移动到c        f(index - 1, b, a, c);//将n-1个盘子从b移动到c    }}int _tmain(int argc, _TCHAR* argv[]){    f(3,1,2,3);    return 0;}
0 0