递归
来源:互联网 发布:淘宝原创服装品牌 编辑:程序博客网 时间: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;}
求阶乘
#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;}
汉诺塔问题
中间过程:
分为三步骤:
(前)“将那坨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
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- 递归
- open ball、closed ball 与 open set、closed set(interior point,limit point)、dense set
- 五大常用算法之--分治算法
- Idea
- [ZJOI2015] 幻想乡战略游戏
- 深度学习框架tensorflow,paddle,mxnet的实战性能对比测试
- 递归
- Zookeeper是什么
- python之sqlite3使用详解
- 排序列表
- [IMWeb训练营作业] Vue.js 仿今日头条 首页
- cron表达式详解
- Xcode运行工程报错-Reason: image not found
- 获取Android “/asset”目录数据
- 搭建yum私有仓库