您的位置:首页 > 其它

算法-Hanoi塔问题+递归

2017-12-20 12:54 399 查看

N阶Hanoi塔问题

要求:(1) 采用分治策略,写出相应问题的递归算法及程序,(2)要求输出整个搬动过程。

/* 递归演示汉诺塔移动过程(设最上面的一个盘子为第1个盘子) */
include<stdio.h>

//Show the movement of the n-th plate
void move(int n, int x, int y){
printf("the %dth plate from %c to %c\n",n,x+65,y+65);
}

//将n个盘子从A座移到C座的过程(借助B座)
void hanoi(int n, int A, int B, int C){
if(n==1)
move(n,A,C);
else{
hanoi(n-1,A,C,B);
move(n,A,C);
hanoi(n-1,B,A,C);
}

}
//The main function
int main()
{

int n; //Hanoi's total plates
printf("Assuming the top plate is the first plate\nplease input the number of plate : ");
scanf("%d",&n);
hanoi(n,0,1,2);
}


找出n个自然数(1,2,3,…,n)中取r个数的组合。

要求:(1)采用分治策略,写出相应问题的递归算法及程序(2)要求输出所有的r个数的组合。

递归实现

#include<iostream>
using namespace std;
int a[100];
comb(int m,int k){
int i,j;
for(i=m;i>=k;i--){
a[k]=i;
if(k>1)
comb(i-1,k-1);
else{
for(j=a[0];j>0;j--)
cout<<a[j]<<" ";
cout<<endl;
}
}
}
int main(){
int n,r;
cin>>n>>r;
if(r>n)
cout<<"error"<<endl;
else{
a[0]=r;
comb(n,r);
}
}


非递归实现

时间复杂度为O(n^r),且r的大小已知,这样才能确定循环的层数。这种算法对于r比较小的时候可以考虑一下。

#include<iostream>
using namespace std;

int main(){
int n=5,r=3,i,j,k,t;
t=0;
for (i=1;i<=n-r+1;i++)
{
for(j=j+1;i<n-r+2;j++)
{
for(k=j+1;k<=n-r+3;K++)
{
t=t+1;
cout<<i<<":"<<j<<":"<<k<<endl;
}
}
}
cout<<"Total="<<t;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法