程序举例:
选出在N个人中找出K个人有多少种选择:
#include<iostream.h>
void main()
{
int n,k;
long comm(int n,int k);
cout<<"请输入n和k的值,用空格隔开:\n";
cin>>n>>k;
cout<<comm(n,k)<<endl;
}
long comm(int n,int k)
{
if (k>n)
return 0;
else if(n==k||k==0)
return 1;
else
return comm(n-1,k)+comm(n-1,k-1);
}
汉诺塔:
#include<iostream.h>
void move(char getone,char putone)
{cout<<getone<<"-->"<<putone<<endl;}
void hanoi(int n,char one,char two,char three)
{
void move(char getone,char putone);
if (n==1)move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void main()
{
void hanoi(int n,char one,char two,char three);
int m;
cout<<"Enter the number of diskes:";
cin>>m;
cout<<"the steps to moving"<<m<<"diskes:"<<endl;
hanoi(m,'A','B','C');
}