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
看着是有规律但是智商有限总结不出, 查wiki:
The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
For example, given the sequence [1, 2, 3, 4] which starts in a weakly increasing order, and given that the index is zero-based, the steps are as follows:
Following this algorithm, the next lexicographic permutation will be [1,3,2,4], and the 24th permutation will be [4,3,2,1] at which point a[k] <a[k + 1] does not exist, indicating that this is the last permutation.
代码如下:
public class Solution { public void nextPermutation(int[] nums) { if(nums==null || nums.length==0) return; int i = nums.length-2; while(i >= 0 && nums[i] > nums[i + 1]){ i--; } if(i >= 0){ int j = i + 1; while(j < nums.length && nums[j] > nums[i]){ j++; } j--; swap(nums[i], nums[j]); } reverse(nums, i + 1, nums.length - 1); } private void swap(int a, int b){ int tmp = a; a = b; b = tmp; } private void reverse(int[] nums, int left, int right){ while(left < right){ swap(nums[left], nums[right]); left++; right--; } } }
关于 pass by value 的讲解: http://javadude.com/articles/passbyvalue.htm
正确code:
public class Solution { public void nextPermutation(int[] nums) { if(nums==null || nums.length==0) return; int i = nums.length-2; while(i >= 0 && nums[i] >= nums[i + 1]){// >= 而不是 >, 因为有可能有duplicates, 比如 511 i--; } if(i >= 0){ int j = i + 1; while(j < nums.length && nums[j] > nums[i]){ j++; } j--; // swap(nums[i], nums[j]); int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } reverse(nums, i + 1, nums.length - 1); } private void reverse(int[] nums, int i, int j){ while(i < j){ // swap(nums[i], nums[j]); int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; i++; j--; } } }
upgrade on 06/29/2015
public class Solution { public void nextPermutation(int[] nums) { if(nums == null || nums.length < 2) return; int left; int right; for(left = nums.length - 2; left >= 0; left--){ if(nums[left] < nums[left + 1]){ break; } } if(left < 0){ reverse(nums, 0, nums.length - 1); return; } for(right = nums.length - 1; right > left; right--){ if(nums[right] > nums[left]){ break; } } swap(nums, left, right); reverse(nums, left + 1, nums.length - 1); } private void swap(int[] a, int l, int r){ int tmp = a[l]; a[l] = a[r]; a[r] = tmp; } private void reverse(int[] a, int l, int r){ while(l < r){ swap(a, l, r); l++; r--; } } }