组合问题递归实现
以在n个数中选取m(0<m<=n)个数为例,问题可分解为:
1. 首先从n个数中选取编号最大的数,然后在剩下的n-1个数里面选取m-1个数,直到从n-(m-1)个数中选取1个数为止。
2. 从n个数中选取编号次小的一个数,继续执行1步,直到当前可选编号最大的数为m。
很明显,上述方法是一个递归的过程,也就是说用递归的方法可以很干净利索地求得所有组合。
下面是递归方法的实现:
(1)求从数组a[1..n]中任选m个元素的所有组合。
(2)a[1..n]表示候选集,n为候选集大小,n>=m>0。
(3)b[1..M]用来存储当前组合中的元素(这里存储的是元素下标),
(4)常量M表示满足条件的一个组合中元素的个数,M=m,这两个参数仅用来输出结果。
代码实现:
-
#include <iostream>
-
-
using namespace std;
-
-
void combine( int a[], int n, int m, int b[], const int M )
-
{
-
for(int i=n; i>=m; i--)
-
{
-
b[m-1] = i - 1;
-
if (m > 1)
-
combine(a,i-1,m-1,b,M);
-
else
-
{
-
for(int j=M-1; j>=0; j--)
-
cout << a[b[j]] << " ";
-
cout << endl;
-
}
-
}
-
}
-
-
int main()
-
{
-
const int N = 4;
-
int a[N];
-
for(int i=0; i<N; i++)
-
a[i] = i+1;
-
for(int M=1; M <= 4; M++)
-
{
-
-
int b[M];
-
combine(a,N,M,b,M);
-
}
-
return 0;
-
}
运行结果


组合问题及代码实现
原文:http://blog.csdn.net/raochangping/article/details/39803943