Next Permutation

描述

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. 1,2,3 1,3,2
  2. 3,2,1 1,2,3
  3. 1,1,5 1,5,1

分析

算法过程如下图所示(来自http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html)。

下一个排列算法流程

Figure: 下一个排列算法流程

代码

  1. // Next Permutation
  2. // Time Complexity: O(n), Space Complexity: O(1)
  3. class Solution {
  4. public:
  5. void nextPermutation(vector<int> &nums) {
  6. next_permutation(nums, 0, nums.size());
  7. }
  8. private:
  9. bool next_permutation(vector<int> &nums, int begin, int end) {
  10. // From right to left, find the first digit(partitionNumber)
  11. // which violates the increase trend
  12. int p = end - 2;
  13. while (p > -1 && nums[p] >= nums[p + 1]) --p;
  14. // If not found, which means current sequence is already the largest
  15. // permutation, then rearrange to the first permutation and return false
  16. if(p == -1) {
  17. reverse(&nums[begin], &nums[end]);
  18. return false;
  19. }
  20. // From right to left, find the first digit which is greater
  21. // than the partition number, call it changeNumber
  22. int c = end - 1;
  23. while (c > 0 && nums[c] <= nums[p]) --c;
  24. // Swap the partitionNumber and changeNumber
  25. swap(nums[p], nums[c]);
  26. // Reverse all the digits on the right of partitionNumber
  27. reverse(&nums[p+1], &nums[end]);
  28. return true;
  29. }
  30. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/array/next-permutation.html