31. Next Permutation (Array; Math)
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
思路:对大小的影响尽可能小=>影响尽可能右侧的位=>右向左扫描,找到第一个<右侧的数(i)
将右边最小的>nums[i]的数(j)与它交换
从小到大排列i之后的数
规律:
1. 总是最后一个数与之前比它小的最近的那个数交换
2. 如果没有,则看倒数第二个数,以此类推
3. 如果都没有,则返回递增序列
第1、2种情况,两个swap的数之间的数要按从小到大排列
class Solution { public: void nextPermutation(vector<int>& nums) { int size = nums.size(); int swapIndex = size, tmp, i ,j; for(i = size-2; i >= 0; i--){ for(j = i+1; j < size; j++){ if(nums[j] <= nums[i] || (swapIndex<size && nums[j]>=nums[swapIndex])) continue; swapIndex = j; } if(swapIndex>=size) continue; tmp = nums[i]; nums[i]=nums[swapIndex]; nums[swapIndex]=tmp; sort(nums.begin()+i+1, nums.end()); break; } if(i<0){ sort(nums.begin(), nums.end()); } } };