Take the following nums as an exmpel : [2,4,3,1]
The 4, 3, 1 is a decending order, it cannot be larger any more. How we can make 2,4,3,1 larger? we need to find a number in 4,3,1, which is just larger than 2, as 4,3,1 is decending order, so we check from back to front, when we arrive "3", we know it is the the number that we want to find.
Then replace "2" with "3", the nums become 3, 4, 2, 1, we need to reverse 4,2,1 to make it 3,1,2,4, that is the result.
public void nextPermutation(int[] nums) { int index = 0; for (int i = nums.length-1; i > 0; i--) { if (nums[i] > nums[i - 1]) { index = i; break; } } if(index>0) for (int i = nums.length - 1; i >= index; i--) { if (nums[i] > nums[index-1]) { swap(nums, index-1, i); break; } } reverse(nums, index); } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } private void reverse(int[] nums, int index) { int i = index, j = nums.length - 1; while (i < j) { swap(nums, i++, j--); } }
What if the problem is find the Last Permutation? for example [3,1,2,4]
The 1, 2, 4 is a ascending order, it cannot be smaller any more. How can we make 3,1,2,4 smaller? we need to find a number in 1,2,4, which is just smaller than 3, as 1,2,4 is ascending order, so we check from back to front, when we arrive "2", we know it is the number that we want to find.
Then replace "3" with "2", the nums become 2, 1,3,4, we need to reverse 1,3,4 to make it 2,4,3,1, that is the result!
public void nextPermutation(int[] nums) { int index = 0; for (int i = nums.length-1; i > 0; i--) { if (nums[i] < nums[i - 1]) { //here ">" become "<" index = i; break; } } if(index>0) for (int i = nums.length - 1; i >= index; i--) { if (nums[i] < nums[index-1]) { //here ">" become "<" swap(nums, index-1, i); break; } } reverse(nums, index); } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } private void reverse(int[] nums, int index) { int i = index, j = nums.length - 1; while (i < j) { swap(nums, i++, j--); } }