Question:
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Example
[1,3,2,3]
for, the next permutation is[1,3,3,2]
[4,3,2,1]
for, the next permutation is[1,2,3,4]
Note
The list may contains duplicate integers.
What is Next permutation?
The permutation with current charactors, which is lexicographically next.
1234-1243
4321-1234
1243-1324
2134-2143
Idea:
Answer:
classSolution { Public: /** * @param nums:an array of integers * @return: An array of integers that ' s next permuation */vector<int> Nextpermutation (vector<int> &nums) { //Write your code here if(Nums.size () <=1) { returnnums; } //Find first element is smaller that next element intFirst_small_index =-1; for(inti = nums.size ()-2; I >=0; --i) { if(Nums[i] < nums[i+1]) {First_small_index =i; Break; } } //find the first element is just bigger than the element we found if(First_small_index! =-1) { intFirst_bigger_index =First_small_index; for(inti = First_small_index +1; I < nums.size (); ++i) { if(Nums[i] >Nums[first_small_index]) {First_bigger_index =i;}Else { Break; } } swap (Nums[first_small_index], Nums[first_bigger_index]); } //Reverse Rest ArrayReverse (Nums.begin () + First_small_index +1, Nums.end ()); returnnums; }};
[Leetcode 52] Next Permutation report