Permutations

描述

Given a collection of numbers, return all possible permutations.

For example,[1,2,3] have the following permutations:[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

next_permutation()

函数 next_permutation()的具体实现见这节 Next Permutation

  1. // Permutations
  2. // 重新实现 next_permutation()
  3. // 时间复杂度O(n!),空间复杂度O(1)
  4. class Solution {
  5. public:
  6. vector<vector<int> > permute(vector<int> &num) {
  7. vector<vector<int> > result;
  8. sort(num.begin(), num.end());
  9. do {
  10. result.push_back(num);
  11. // 调用的是 2.1.12 节的 next_permutation()
  12. // 而不是 std::next_permutation()
  13. } while(next_permutation(num.begin(), num.end()));
  14. return result;
  15. }
  16. private:
  17. // 代码来自 2.1.12 节的 next_permutation()
  18. void nextPermutation(vector<int> &nums) {
  19. next_permutation(nums.begin(), nums.end());
  20. }
  21. template<typename BidiIt>
  22. bool next_permutation(BidiIt first, BidiIt last) {
  23. // Get a reversed range to simplify reversed traversal.
  24. const auto rfirst = reverse_iterator<BidiIt>(last);
  25. const auto rlast = reverse_iterator<BidiIt>(first);
  26. // Begin from the second last element to the first element.
  27. auto pivot = next(rfirst);
  28. // Find `pivot`, which is the first element that is no less than its
  29. // successor. `Prev` is used since `pivort` is a `reversed_iterator`.
  30. while (pivot != rlast && *pivot >= *prev(pivot))
  31. ++pivot;
  32. // No such elemenet found, current sequence is already the largest
  33. // permutation, then rearrange to the first permutation and return false.
  34. if (pivot == rlast) {
  35. reverse(rfirst, rlast);
  36. return false;
  37. }
  38. // Scan from right to left, find the first element that is greater than
  39. // `pivot`.
  40. auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));
  41. swap(*change, *pivot);
  42. reverse(rfirst, pivot);
  43. return true;
  44. }
  45. };

递归

本题是求路径本身,求所有解,函数参数需要标记当前走到了哪步,还需要中间结果的引用,最终结果的引用。

扩展节点,每次从左到右,选一个没有出现过的元素。

本题不需要判重,因为状态装换图是一颗有层次的树。收敛条件是当前走到了最后一个元素。

代码

  1. // Permutations
  2. // 深搜,增量构造法
  3. // 时间复杂度O(n!),空间复杂度O(n)
  4. class Solution {
  5. public:
  6. vector<vector<int> > permute(vector<int>& num) {
  7. sort(num.begin(), num.end());
  8. vector<vector<int>> result;
  9. vector<int> path; // 中间结果
  10. dfs(num, path, result);
  11. return result;
  12. }
  13. private:
  14. void dfs(const vector<int>& num, vector<int> &path,
  15. vector<vector<int> > &result) {
  16. if (path.size() == num.size()) { // 收敛条件
  17. result.push_back(path);
  18. return;
  19. }
  20. // 扩展状态
  21. for (auto i : num) {
  22. // 查找 i 是否在path 中出现过
  23. auto pos = find(path.begin(), path.end(), i);
  24. if (pos == path.end()) {
  25. path.push_back(i);
  26. dfs(num, path, result);
  27. path.pop_back();
  28. }
  29. }
  30. }
  31. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/brute-force/permutations.html