Topic:
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
Test instructions: Find the next number of permutations
Idea: The main is based on experience, to remember the law of the number of permutations to find
(1) First from the backward to find the first drop position, recorded as I, if there is no proof is the last sort, the next is the reverse of the original string
(2) from I, I find the corresponding value of the smallest of the corresponding index (because the following are descending, so that the first value is less than equal to the number of the previous one is the request), if not the length-1;
Note: (for example, 2,3,6,5,4,1 the first descending is 3:3 large, the smallest of which is 4)
(3) Exchange Nums[i] and Nums[index]
(4) Reverse the back of I
Code:
Public classSolution { Public voidNextpermutation (int[] nums) { if(Nums.length < 2) return; for(inti = nums.length-2; I >= 0; i--) { if(Nums[i] < nums[i+1]) { intindex = nums.length-1; for(intj = i + 1; J < Nums.length; J + +) {//to find the smallest one larger than Nums[index] if(Nums[j] <= nums[i]) {//Be sure to have an equal sign!index = j-1; Break; } } inttemp =Nums[i]; Nums[i]=Nums[index]; Nums[index]=temp; Reverse (nums, I+1, Nums.length-1); return; }} reverse (Nums,0, Nums.length-1); return; } Public voidReverseint[] Nums,intBeginintend) { if(Begin = =end)return; while(Begin <end) { inttemp =Nums[begin]; Nums[begin]=Nums[end]; Nums[end]=temp; Begin++; End--; } } }
[Leetcode-java] Next permutation