[关闭]
@CrazyHenry 2018-01-04T20:51:53.000000Z 字数 2043 阅读 1876

Leetcode31. Next Permutation

ddddLeetcode刷题


44299-106.jpg-285.5kB

Implement(使用,实施) next permutation(排列), which rearranges numbers into the lexicographically(字典序的) next greater(更大的) permutation(排列) of numbers.

If such arrangement is not possible, it must rearrange it as the lowest(最小的) possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

优秀代码:

分析:
image.png-124.7kB

  1. //Leetcode-31
  2. //T(n)=O(n),S(n)=O(1)
  3. class Solution
  4. {
  5. public:
  6. void nextPermutation(vector<int> &nums)
  7. {
  8. next_permutation(nums.begin(), nums.end());
  9. }
  10. template<typename BidiIt>
  11. bool next_permutation(BidiIt first, BidiIt last)
  12. {
  13. // Get a reversed range to simplify reversed traversal.
  14. const auto rfirst = reverse_iterator<BidiIt>(last);
  15. const auto rlast = reverse_iterator<BidiIt>(first);
  16. // Begin from the second last element to the first element.
  17. auto pivot = next(rfirst);
  18. // Find `pivot`, which is the first element that is no less than its
  19. // successor. `Prev` is used since `pivort` is a `reversed_iterator`.
  20. while (pivot != rlast && *pivot >= *prev(pivot))
  21. ++pivot;
  22. // No such elemenet found, current sequence is already the largest
  23. // permutation, then rearrange to the first permutation and return false.
  24. if (pivot == rlast)
  25. {
  26. reverse(rfirst, rlast);
  27. return false;
  28. }
  29. // Scan from right to left, find the first element that is greater than
  30. // `pivot`.
  31. auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));
  32. swap(*change, *pivot);
  33. reverse(rfirst, pivot);
  34. return true;
  35. }
  36. };

image.png-170kB

这段代码利用了非常多C++11的特性,非常大气,但是也比较难理解,需要好好思考:

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注