分治算法与递归(练习)

1.兔子数列

#include<iostream>
using namespace std;
//函数功能:求斐波那契数列的某一项的值
//输入参数:第n个元素 
int fib(int n){
	if(n<=1) return 1;
	return fib(n-1)+fib(n-2);//递归调用 
}

int main(){
	int m;
	cin>>m;
	m=fib(m);
	//printf("%d ",m);
	cout<<m<<endl;
	return 0;
}

2.汉诺塔问题

#include<iostream>
#include<cmath>
using namespace std;
//函数功能:汉诺塔递归求解 移动路径和移动步数
//n:圆盘个数 x,y,z表示三个塔座
//n为1的移动情况 
void move(char A,char C){
	printf("%c---->%c\n",A,C);
} 
void hannot_tower(int n,char x,char y,char z){
     if(n==1) move(x,z);
     else{
     	hannot_tower(n-1,x,z,y);//借助塔座C奖n-1个圆盘由A移动到B
		move(x,z);//将第n个圆盘将塔座A移动到塔座C
		hannot_tower(n-1,y,x,z);//借助塔座A将塔座B上的n-1个圆盘移动到塔座C 
     	
     	
	 }
}
int main(){
  int n;
  char A='A',B='B',C='C';
  int total_p;
  cin>>n;
  hannot_tower(n,A,B,C);	
  total_p=pow(2,n)-1;
  printf("%d ",total_p);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IKUN家族

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值