Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.ide
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).spa
The replacement must be in-place, do not allocate extra memory.code
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.blog
1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1
思路:对于[a0,a1,...,an]中的ai,若是知足ai>=ai-1>=...>=an,那么序列[ai,ai-1,...,an]就是由构成的序列的ai,ai-1,...,an最大序列,对应的由构成的最小序列就是将最大序列反转的[an,an-1,...,ai]。对于当前序列[a0,a1,...,an],若是存在比之更大的序列,那么新的序列A应该是比当前序列大的序列中最小的。由后向前看:leetcode
1.若是an>an-1,那么只要交换an和an-1就能够获得序列A。get
2.an-1>=an时,若是an-2比an-1小的话,例如an-1>an-2>=an,只要替换an-2和an-1,就能够获得序列A。it
...io
能够看到,若是ai不知足ai>=ai-1>=...>=an对,只要在ai-1,...,an中找到大于ai的最小值ak,交换ai和ak,而后将ai-1,...,ai,...,an反转,就能够获得序列A。首先a1,...,ai+1不变,将ai和ak交换后,仍然知足ai-1>=...>=ai>=...>=an,将[ai-1,ai,..,an]反转,就能够获得离[ai,...,ak,...,an]最近的大于的序列[ak,an-1,...,ai,...,ai-1],这样就控制了变换后第i位是当前状况的最小值,而后剩余元素又组成了剩余元素能够组成的最小值。class
代码:im
1 public class Solution { 2 public void nextPermutation(int[] nums) { 3 int i, j; 4 for (i = nums.length - 2; i >= 0 && nums[i] >= nums[i+1]; --i); 5 if (i >= 0) { 6 for (j = i + 1; j < nums.length && nums[i] < nums[j]; ++j); 7 swap(nums, i, j - 1); 8 } 9 i++; 10 j = nums.length - 1; 11 while (i < j) { 12 swap(nums, i++ ,j--); 13 } 14 } 15 public void swap(int[] nums, int i, int j) { 16 nums[i] += nums[j]; 17 nums[j] = nums[i] - nums[j]; 18 nums[i] -= nums[j]; 19 } 20 }