Next permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must is in-place, do not allocate extra memory.
Here is some examples. Inputs is in the left-hand column and its corresponding outputs is in the right-hand column.
1,2,3
→1,3,2
3,2,1
→1,2,3
1,1,5
→1,5,1
https://leetcode.com/problems/next-permutation/
Find the next arrangement.
The size of the string is a bit to compare, the next arrangement is just larger than the current arrangement.
The simplest case is [1, 2, 3], and only the last two bits are exchanged to get the next sequence.
The complex case [1, 2, 4, 3], found that the last substring [4, 3] is already the largest, then need to move a number 2 to the front, and the back substring to be incremented [3, 2], the result is [4, 1, 3, 2].
Again such as [1, 4, 7, 5, 3, 2], the result is [1, 5, 2, 3, 4, 7]
The realization of the time, first judge is not descending sequence, if it is reverse all,
Otherwise, first swap one bit, reverse the back of the substring.
1 /**2 * @param {number[]} nums3 * @return {void} does not return anything, modify Nums in-place instead.4 */5 varNextpermutation =function(nums) {6 for(vari = nums.length-1; I > 0 && nums[i] <= nums[i-1]; i--);7 if(i = = 0){8Reverse (0, Nums.length-1);9 return;Ten } One for(varj = i + 1; J < Nums.length && Nums[i-1] < nums[j]; J + +); ASwap (i-1, j-1); -Reverse (i, nums.length-1); - return; the - functionreverse (start, end) { - while(Start <end) { - swap (start, end); +start++; -end--; + } A } at functionSwap (I, j) { - varTMP =Nums[i]; -Nums[i] =Nums[j]; -NUMS[J] =tmp; - } -};
[Leetcode] [JavaScript] Next permutation