#include <iostream>
using namespace std;
int count;
int sum(int *array,int n)
{
if(n==0)
return 0;
else
return (sum(array,n-1)+array[n-1]);
}
void initSum()
{
int array[20];
int sum1 = 0;
for(int i=0;i<20;i++)
{
array[i] = i;
sum1 +=i;
}
cout<<"the sum of array = "<<sum(array,20)<<endl;
cout<<sum1<<endl;
}
template <typename T>
void Swap(T &x,T &y)
{
T temp;
temp = x;
x = y;
y = temp;
}
template <typename T>
void Perm(T list[],int k,int m)
{
if(k==m)
{
for(int i=0;i<m;i++)
cout<<list[i];
count++;
cout<<endl;
}
else
{
for(int j=k;j<m;j++)
{
Swap(list[k],list[j]);
Perm(list,k+1,m);
Swap(list[k],list[j]);
}
}
}
void initPerm()
{
int length;
cout<<"input the length of list[] = ";
cin>>length;
char *list = new char [length];
for(int i=0;i<length;i++)
list[i] = (97+i) ;
Perm(list,0,length);
cout<<length<<"个字母排列的个数为 = "<<count<<endl;
}
int main()
{
//initSum(); /*n个元素递归求和*/
initPerm(); /*n个字母的全排列打印输出*/
return 0;
}
通过递归求集合的全排列,你将会加深对递归的理解。写递归函数最重要的是从两个全局把握:
(1)递归的结束条件
(2)第一次递归的详细情况
从全局弄清第一次递归很重要,很多人总是一下就陷入了一层又一层的递归,不能从整体上把握问题,而导致写不出递归函数,这里指的整体把握是:只考虑从n到n-1时能把问题全部解决的具体细节,那本程序为例即
for(int j=k;j<m;j++)
{
Swap(list[k],list[j]);
Perm(list,k+1,m);
Swap(list[k],list[j]);
}
执行完这个过程(即for循环运行完后才是第一轮)所求问题就解决了,而不要一上来就从Perm(list,k+1,m)开始一直递归下去。
本文通过递归方式实现数组元素求和及字符全排列,并详细解释了递归函数的两个关键点:递归结束条件与首次递归的具体细节。通过实例帮助理解递归原理。
644

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



