假设给我:
- 整数范围
iRange
(即从1
到iRange
)和 - 所需数量的组合
我想找到所有可能组合的数量并打印出所有这些组合。
例如:
给定:iRange = 5
和n = 3
那么组合的数量就是iRange! / ((iRange!-n!)*n!) = 5! / (5-3)! * 3! = 10
组合,输出为:
123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345
另一个例子:
给定:iRange = 4
和n = 2
那么组合的数量就是iRange! / ((iRange!-n!)*n!) = 4! / (4-2)! * 2! = 6
组合,输出为:
12 - 13 - 14 - 23 - 24 - 34
到目前为止,我的尝试是:
#include <iostream>
using namespace std;
int iRange= 0;
int iN=0;
int fact(int n)
{
if ( n<1)
return 1;
else
return fact(n-1)*n;
}
void print_combinations(int n, int iMxM)
{
int iBigSetFact=fact(iMxM);
int iDiffFact=fact(iMxM-n);
int iSmallSetFact=fact(n);
int iNoTotComb = (iBigSetFact/(iDiffFact*iSmallSetFact));
cout<<"The number of possible combinations is: "<<iNoTotComb<<endl;
cout<<" and these combinations are the following: "<<endl;
int i, j, k;
for (i = 0; i < iMxM - 1; i++)
{
for (j = i + 1; j < iMxM ; j++)
{
//for (k = j + 1; k < iMxM; k++)
cout<<i+1<<j+1<<endl;
}
}
}
int main()
{
cout<<"Please give the range (max) within which the combinations are to be found: "<<endl;
cin>>iRange;
cout<<"Please give the desired number of combinations: "<<endl;
cin>>iN;
print_combinations(iN,iRange);
return 0;
}
我的问题:
我的代码中与组合打印相关的部分仅适用于n = 2, iRange = 4
并且我不能使其一般工作,即适用于任何n
and iRange
。