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. public class Solution {
  4. public void nextPermutation(int[] nums) {
  5. nextPermutation(nums, 0, nums.length);
  6. }
  7. private static boolean nextPermutation(int[] nums, int begin, int end) {
  8. // From right to left, find the first digit(partitionNumber)
  9. // which violates the increase trend
  10. int p = end - 2;
  11. while (p > -1 && nums[p] >= nums[p + 1]) --p;
  12. // If not found, which means current sequence is already the largest
  13. // permutation, then rearrange to the first permutation and return false
  14. if(p == -1) {
  15. reverse(nums, begin, end);
  16. return false;
  17. }
  18. // From right to left, find the first digit which is greater
  19. // than the partition number, call it changeNumber
  20. int c = end - 1;
  21. while (c > 0 && nums[c] <= nums[p]) --c;
  22. // Swap the partitionNumber and changeNumber
  23. swap(nums, p, c);
  24. // Reverse all the digits on the right of partitionNumber
  25. reverse(nums, p+1, end);
  26. return true;
  27. }
  28. private static void swap(int[] nums, int i, int j) {
  29. int tmp = nums[i];
  30. nums[i] = nums[j];
  31. nums[j] = tmp;
  32. }
  33. private static void reverse(int[] nums, int begin, int end) {
  34. end--;
  35. while (begin < end) {
  36. swap(nums, begin++, end--);
  37. }
  38. }
  39. };

相关题目

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