1、递归枚举
1 #include<iostream> 2 using namespace std; 3 4 void print_permutation(int n, int *p, int cur) 5 { 6 if (cur == n) 7 { 8 for (int i = 0; i < n; i++) 9 cout << p[i]; 10 cout << endl; 11 } 12 else for (int i = 1; i <= n; i++) 13 { 14 int ok = 1; 15 for (int j = 0; j < cur; j++) 16 if (p[j] == i) ok = 0; 17 if (ok) 18 { 19 p[cur] = i; 20 print_permutation(n, p, cur + 1); 21 } 22 } 23 } 24 int _tmain(int argc, _TCHAR* argv[]) 25 { 26 int n,p[10000],cur=0; 27 cin >> n; 28 print_permutation(n, p, cur); 29 return 0; 30 }
2、STL——next_permutation
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 5 int _tmain(int argc, _TCHAR* argv[]) 6 { 7 int n, p[10]; 8 cin >> n; 9 for (int i = 0; i < n; i++) 10 cin >> p[i]; 11 sort(p, p + n); 12 do{ 13 for (int i = 0; i < n; i++) 14 cout << p[i]; 15 cout << endl; 16 } while (next_permutation(p, p + n)); 17 return 0; 18 }
时间: 2024-10-12 16:32:50