给定一个数字m和数字n,从n个数(即1,2,3,4,。...n)中选m个数总共有C(n,m)种序列。输出对于n,m的所有这种排列
当n=5,m=3,即C(5,3)输出10种序列
5 4 3
5 4 2
5 4 1
5 3 2
5 3 1
5 2 1
4 3 2
4 3 1
4 2 1
3 2 1
分析:可以从第一个数开始选择,因为(3,4,5)与(5,4,3)是算作一种序列的,所以呢为了避免重复,我们可以从大到小输出
该排列中的数大小依次递减,第一个数最大,最后一个数最小
第一个数字可以选择m到n的(n-m+1)个数,然后采用递归的方式即可,终止条件为m=0时
#include<iostream>
#include<string>
using namespace std;
//size is equal to m when function is first time
//invocated
void combination(int m,int n,int *A,int size){
if(m==0){
for(int i=size-1;i>=0;i--)
cout<<A[i]<<" ";
cout<<endl;
return;
}
for(int i=n;i>=m;i--){
A[m-1]=i;
combination(m-1,i-1,A,size);
}
}
int main(){
int *A=new int[100];
combination(3,6,A,3);
}
刚开始很废的写了一个字符串的算法
#include<iostream>
#include<string>
using namespace std;
//int *a=new int[m];
void combination(int m,int n,string str){
if(m==0){
cout<<str;
cout<<endl;
return;
}
for(int i=n;i>=m;i--){
//cout<<i<<" ";
char buf[10];
sprintf(buf, "%d",i);
string b=buf;
if(i<n){
str=str.substr(0,str.size()-1);
}
str+=b;
combination(m-1,i-1,str);
}
}
int main(){
combination(3,6," ");
}