Problem
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
Analysis
Check http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html
In specific, we have the following steps
Step 1: scan from right to left, find the first index that violates the non-decreasing property, denote as vioIdx
Step 2: scan from right to left, find the first index of number that is smaller than vioIdx, and swap the values
Step 3: reverse the array on the right side of the value
Solution
class Solution { public: void nextPermutation(vector<int>& nums) { //Step 1: from right to left, find the first one that violates the non-decreasing trend int vioIdx = nums.size()-1; while(vioIdx > 0 && nums[vioIdx] <= nums[vioIdx-1]){ vioIdx--; } if(vioIdx > 0){ vioIdx--; //Step 2: from right to left, find the first one that is larger than nums[vioIdx] int rightIdx = nums.size()-1; while(rightIdx > 0 && nums[rightIdx] <= nums[vioIdx]){ rightIdx--; } int swap = nums[vioIdx]; nums[vioIdx] = nums[rightIdx]; nums[rightIdx] = swap; //Step 3: preparation, reverse the array from the righthand side of vioidx vioIdx++; } //Step 3: reverse int end = nums.size()-1; while(end>vioIdx){ int swap = nums[vioIdx]; nums[vioIdx] = nums[end]; nums[end] = swap; vioIdx++; end--; } } };