【发布时间】:2010-12-24 23:47:05
【问题描述】:
假设给定我:
- 整数范围
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 和iRange。
【问题讨论】:
-
几点-请以问题的形式提出您的要求。另外,想想你在问什么。我相信您正在寻找的是一种置换算法(iRange P n),它是从“iRange”值中选择的“n”个数字的所有组合。
-
在您的示例输出中:
123 - 124 - 125 - 134 - 135 - 142 - 145 - 234 - 245 - 345,您有124和142,看起来像一个排列。一个组合应该让你:123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345. -
我要求的是帮助/想法/指导来更改 for 循环,以便我的代码适用于 n 和 iRange 的任何值,并像示例中那样产生输出。我认为也许 for 循环应该被另一个递归函数替换,或者将当前函数转换为递归函数。但我想不出递归的基本情况。
-
@Mike DeSimone 谢谢我刚刚纠正了它。
-
next_combination在 Google 中的第一次点击是不错的读物:sites.google.com/site/hannuhelminen/next_combination
标签: c++ combinations