2015/06/23

【C++】一個簡單的列出所有組合的程式





?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <cstdio>
#include <queue>
#define MAX 5 //輸入數字總數
 
using namespace std;
 
int n[MAX], color[MAX];
 
void dfs(int count, int num, queue<int> q){
    q.push(num);
    if (count==MAX){
        while (!q.empty()) {
            printf("%d ", q.front());
            q.pop();
        }
        printf("\n");
        return;
    }
    for (int i=0; i< MAX; i++) {
        if (!color[i]) {
            color[i] = 1;
            dfs(count+1, n[i], q);
            color[i] = 0;
        }
    }
}
 
int main(){
    while (scanf("%d", &n[0]) && n[0]) {
        for (int i=1; i < MAX; i++) scanf("%d", &n[i]);
        for (int i=0; i< MAX; i++) {
            for (int j=0; j< MAX; j++) color[j] = 0;
            color[i] = 1;
            queue<int> q;
            dfs(1, n[i], q);
        }
    }
    return 0;
}