#Leetcode# 31. Next Permutation
https://leetcode.com/problems/next-permutation/
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 and use only constant 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
代码:
class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(); int temp1, temp2; for(int i = n - 2; i >= 0; i --) { if(nums[i + 1] > nums[i]) { temp1 = i; for(int j = n - 1; j > temp1; j --) { if(nums[j] > nums[i]) { temp2 = j; break; } } swap(nums[temp1], nums[temp2]); reverse(nums.begin() + i + 1, nums.end()); return ; } } reverse(nums.begin(), nums.end()); } };
从后向前找到第一个后面数字比前面小的位置 然后确定这个位置 再从后向前找出第一个比该数字大的位置 然后交换着两个数字 然后这两个数字之后对应的部分也要逆序 用到 $reverse$ 函数进行反转 做法 get!!!