C++递归调用

来源:互联网 发布:淘宝人群画像工具 编辑:程序博客网 时间:2024/06/05 17:32

程序举例:

选出在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;elsereturn 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');}


0 0
原创粉丝点击