我在這裏查了幾乎所有類似的帖子,但我無法弄清楚我怎麼能做到我想要的。我試圖是給輸入在C程序,讓說,4號,程序返回下面的號碼數組:生成數字組合而不重複的算法
1
2
3
4
12
13
14
23
24
34
123
134
124
1234
更清楚: 如果輸入的數字是4則我想使用數字1-4並生成所有可能的數字組合(從1位數組合到4位數組合),無需重複數字。
我嘗試以下的代碼:
#include <stdio.h>
/* Prints out a combination like {1, 2} */
void printc(int comb[], int k) {
printf("{");
int i;
for (i = 0; i < k; ++i)
printf("%d, ", comb[i] + 1);
printf("\\b\\b}\\n");
}
int next_comb(int comb[], int k, int n) {
int i = k - 1;
++comb[i];
while ((i >= 0) && (comb[i] >= n - k + 1 + i)) {
--i;
++comb[i];
}
if (comb[0] > n - k) /* Combination (n-k, n-k+1, ..., n) reached */
return 0; /* No more combinations can be generated */
/* comb now looks like (..., x, n, n, n, ..., n).
Turn it into (..., x, x + 1, x + 2, ...) */
for (i = i + 1; i < k; ++i)
comb[i] = comb[i - 1] + 1;
return 1;
}
int main(int argc, char *argv[]) {
int n = 5; /* The size of the set; for {1, 2, 3, 4} it's 4 */
int k = 3; /* The size of the subsets; for {1, 2}, {1, 3}, ... it's 2 */
int comb[16]; /* comb[i] is the index of the i-th element in the
combination */
/* Setup comb for the initial combination */
int i;
for (i = 0; i < k; ++i)
comb[i] = i;
/* Print the first combination */
printc(comb, k);
/* Generate and print all the other combinations */
while (next_comb(comb, k, n))
printc(comb, k);
return 0;
}
上述程序輸出結果。我想以某種方式得到結果..但我不能,因爲上面的代碼以奇怪的方式打印結果。
而你的問題是......? – 2013-04-26 16:42:29
你正試圖展示原始輸入的某種排列?你的問題不是很清楚。 – 2013-04-26 16:49:57
我修正了輸出並添加了一個更好的解釋 – Dchris 2013-04-26 16:54:10