算法竞赛宝典 递推算法 汉诺塔

//汉诺塔的步数问题,H(n)=H(n-1)*2+1,使用迭代的方法求出通项公式

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main()
{
	int n;
	while(cin>>n)
	    printf("%d\n",(1<<n)-1);
	return 0;
}

//实现汉诺塔的搬运步骤,其实就是递归实现,以前第一次接触递归的时候,怎么也看不懂这个算法的实现

//当时一头雾水,不知道怎么思考,后来多写了递归这类的题目,了解了递归的思想后,就可以直接码出来了

//最重要的还是通过题目不断的理解,感觉每一种算法的思想都是这样,需要通过不断的做题,不断的思考,

//才能理解的的更加透彻

#include<iostream>
#include<bits/stdc++.h>

using namespace std;

void move(int n,char a,char b,char c)
{
	if(n==1)
	{
		printf("move %d from %c to %c\n",n,a,c);
		return ;
	}
	move(n-1,a,c,b);    //注意代表的字母意思
	printf("move %d from %c to %c\n",n,a,c);    
	move(n-1,b,a,c);
} 
int main()
{
	int n;
	while(cin>>n)
	    move(n,'A','B','C');
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CJ_035/article/details/79766853