1. 1-N 全排列 #include <iostream> using namespace std; #define N 1001 int rcd[N]; int used[N]; int num[N]; int n; void permutation(int l) { if(l == n) { for(int i = 0; i < n; i++) { cout << rcd[i] << " "; } cout << endl; } else { for(int i = 0; i < n; i++) { if (!used[i]) { used[i] = 1; rcd[l] = num[i]; permutation(l + 1); used[i] = 0; } } } } int readData() { int i; if( scanf("%d", &n) == EOF) { return 0; } for(int i = 0; i < n; i++) scanf("%d", &num[i]); for(int i = 0; i < n; i++) used[i] = 0; return 1; } int main() { while(readData()) { permutation(0); } } 2. 可重集的排列 方法1: 递归枚举 #include <iostream> using namespace std; #define N 1001 int rcd[N]; int used[N]; int num[N]; int n; int m; void unrepeatPermutation(int l) { if(l == n) { for(int i = 0; i < n; i++) { cout << rcd[i] << " "; } cout << endl; } else { for(int i = 0; i < m; i++) { if (used[i] > 0) { used[i]--; rcd[l] = num[i]; unrepeatPermutation(l + 1); used[i]++; } } } } int readData() { int i, j, val; if( scanf("%d", &n) == EOF) { return 0; } m = 0; for(int i = 0; i < n; i++) { scanf("%d", &val); for(j = 0; j < m; j++) { if(num[j] == val) { used[j]++; break; } } if(j == m) { num[m] = val; used[m] = 1; m++; } } return 1; } int main() { while(readData()) { unrepeatPermutation(0); } } 方法2: next_permutation // next_permutation #include <iostream> #include <algorithm> using namespace std; int main () { int myints[] = {1,1,2}; cout << "The possible permutations with 3 elements:/n"; sort (myints,myints+3); do { cout << myints[0] << " " << myints[1] << " " << myints[2] << endl; } while ( next_permutation (myints,myints+3) ); return 0; } 运行结果: The possible permutations with 3 elements: 1 1 2 1 2 1 2 1 1