所以,我正在为我的问题寻找一个好的解决方案。
我需要生成(打印)整数列表的所有组合,例如:如果数组包含从 0 到 n-1 的整数,其中 n = 5:
int array[] = {0,1,2,3,4};
组合中整数的顺序并不重要,这意味着 {1,1,3}、{1,3,1} 和 {3,1,1} 实际上是相同的组合,因为它们都包含一个 3 和两个 1。
所以对于上面的数组,长度为 3 的所有组合:
0,0,0 -> the 1st combination
0,0,1
0,0,2
0,0,3
0,0,4
0,1,1 -> this combination is 0,1,1, not 0,1,0 because we already have 0,0,1.
0,1,2
0,1,3
0,1,4
0,2,2 -> this combination is 0,2,2, not 0,2,0 because we already have 0,0,2.
0,2,3
.
.
0,4,4
1,1,1 -> this combination is 1,1,1, not 1,0,0 because we already have 0,0,1.
1,1,2
1,1,3
1,1,4
1,2,2 -> this combination is 1,2,2, not 1,2,0 because we already have 0,1,2.
.
.
4,4,4 -> Last combination
现在我为此编写了代码,但我的问题是:如果数组中的数字不是从 0 到 n-1 的整数,假设数组是这样的
int array[] = {1,3,6,7};
我的代码不适用于这种情况,任何用于解决此问题的算法或代码,,
这是我的代码:
unsigned int next_combination(unsigned int *ar, int n, unsigned int k){
unsigned int finished = 0;
unsigned int changed = 0;
unsigned int i;
for (i = k - 1; !finished && !changed; i--) {
if (ar[i] < n - 1) {
/* Increment this element */
ar[i]++;
if (i < k - 1) {
/* Make the elements after it the same */
unsigned int j;
for (j = i + 1; j < k; j++) {
ar[j] = ar[j - 1];
}
}
changed = 1;
}
finished = i == 0;
}
if (!changed) {
/* Reset to first combination */
for (i = 0; i < k; i++){
ar[i] = 0;
}
}
return changed;
}
这是主要的:
int main(){
unsigned int numbers[] = {0, 0, 0, 0, 0};
const unsigned int k = 3;
unsigned int n = 5;
do{
for(int i=0 ; i<k ; ++i)
cout << numbers[i] << " ";
cout << endl;
}while (next_combination(numbers, n, k));
return 0;
}