全排列问题这个是用递归实现的
#include<stdio.h>
int cout=1;
int n=0;
void print(int *a)
{
int i=0;
printf("%2d ",cout++);
for(i=0;i<n;i++)
printf("%d",a[i]);
printf("\n");
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void allsort(int *a,int n)
{
if(n==1)
print(a);
else
{
int i;
for(i=0;i<n;i++)
{
swap(a[n-1],a[i]);
allsort(a,n-1);
swap(a[n-1],a[i]);
}
}
}
int main()
{
int a[4]={1,2,3,4};
n=4;
allsort(a,n);
return 0;
}
汉诺塔
#include<iostream>
using namespace std;
void hanoi(int n,char a,char b,char c)
{
if(n>0)
{
hanoi(n-1,a,c,b);
cout<<a<<"-"<<c<<endl;
hanoi(n-1,c,b,a);
}
}
int main()
{
hanoi(3,'a','b','c');
return 0;
}

本文通过两个具体的递归算法案例——全排列问题和汉诺塔问题,深入浅出地介绍了递归算法的设计思想及其实现过程。首先展示了如何使用递归解决全排列问题,并给出了详细的C语言代码实现;随后讲解了经典的汉诺塔问题及其递归解决方案。

583

被折叠的 条评论
为什么被折叠?



