例题:生成排列

For example, the permutations of {0,1,2} are (0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1) and (2,1,0).

  1. // Each function call adds a new element to permutation.
  2. // The array chosen indicates which elements are already included in the permutation.
  3. // If the size of permutation equals the size of the set, a permutation has been generated.
  4. void search() {
  5. if (permutation.size() == n) {
  6. // process permutation
  7. return ;
  8. }
  9. for (int i = 0; i < n; i++) {
  10. if (chosen[i]) continue;
  11. chosen[i] = true;
  12. permutation.push_back(i);
  13. search();
  14. chosen[i] = false;
  15. permutation.pop_back();
  16. }
  17. }
  18. search(); //调用
  1. // The C++ standard library contains the function next_permutation
  2. // that can be used for this
  3. vector<int> permutation;
  4. for (int i = 0; i < n; i++) {
  5. permutation.push_back(i);
  6. }
  7. do {
  8. // process permutation
  9. } while (next_permutation(permutation.begin(),permutation.end()));

例题:递归实现排列型枚举

排列枚举

  1. //用数组存方案
  2. //注意一下 0-index,如果是 1-index 呢?递归的边界是....什么?(提问)
  3. void dfs(int k)
  4. {
  5. if (k == n)
  6. {
  7. for (int i = 0; i < n; i++)
  8. cout << order[i] << ' ';
  9. puts("");
  10. }
  11. for (int i = 1; i <= n; i++)
  12. {
  13. if (chosen[i]) continue;
  14. order[k] = i;
  15. chosen[i] = true;
  16. dfs(k + 1);
  17. chosen[i] = false;
  18. }
  19. }
  1. // 用vector来存方案,用二进制数来记录状态
  2. vector<int> path;
  3. void dfs(int u, int state)
  4. {
  5. if (u == n)
  6. {
  7. vector<int>::iterator i;
  8. for (i = path.begin(); i < path.end(); i++)
  9. cout << *i << ' ';
  10. puts("");
  11. }
  12. for (int i = 0; i < n; i++)
  13. if (!(state >> i & 1))
  14. {
  15. path.push_back(i + 1); //用vector来记录方案
  16. dfs(u + 1, state | 1 << i);
  17. path.pop_back();
  18. }
  19. }

NOIP 2012 普及组初赛试题,排列数

排列数 输入两个正整数n,m(1<n<20,1<m<n),在1~n中任取m个数,按字典序从小到大输出所有这样的排列。

  1. //用贪心的方法,贪出来字典序
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. const int N = 110;
  5. int data[N];
  6. bool used[N];
  7. int n, m;
  8. int main()
  9. {
  10. cin >> n >> m;
  11. //第一种方案存了起来
  12. for (int i = 1; i <= m; i++){
  13. data[i] = i;
  14. used[i] = true;
  15. }
  16. bool flag = true;
  17. while (flag){
  18. //输出方案
  19. for (int i = 1; i <= m; i++) cout << data[i] << ' ';
  20. puts("");
  21. flag = false;
  22. for (int i = m; i >= 1; i--){
  23. used[data[i]] = false;
  24. for (int j = data[i] + 1; j <= n; j++){
  25. if (used[j] == false){
  26. data[i] = j;
  27. used[j] = true;
  28. flag = true;
  29. break;
  30. }
  31. }
  32. if (flag){
  33. for (int k = i + 1; k <= m; k++)
  34. for (int j = 1; j <= n; j++)
  35. if (used[j] == false){
  36. used[j] = true;
  37. data[k] = j;
  38. break;
  39. }
  40. break;
  41. }
  42. }
  43. }
  44. return 0;
  45. }