31. 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, 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
1 class Solution { 2 public: 3 void nextPermutation(vector<int>& nums) { 4 5 //1,2,3,4,6,5---> 1,2,3,(4) 6, (5)-swap--> 1,2,3,5,(6,4) -reverse-> 1,2,3,5,4,6 6 //先找出最大的索引 k 满足 nums[k] < nums[k+1],如果不存在,就翻转整个数组; 7 //再找出另一个最大索引 l 满足 nums[l] > nums[k]; 8 //交换 nums[l] 和 nums[k]; 9 //最后翻转 nums[k+1:]。 10 11 //先找出最大的索引 k 满足 nums[k] < nums[k+1],如果不存在,就翻转整个数组; 12 int i = nums.size()-2; 13 while(i>=0 && nums[i+1]<=nums[i]) { 14 i--; 15 } 16 //再找出另一个最大索引 l 满足 nums[l] > nums[k]; 17 int j = nums.size() -1; 18 if (i>=0) { 19 while(j >=0 && nums[j]<=nums[i]) { 20 j--; 21 } 22 //交换 nums[l] 和 nums[k]; 23 swap(nums[j],nums[i]); 24 //最后翻转 nums[k+1:]。 25 reverse(nums.begin()+i+1,nums.end()); 26 } else { 27 reverse(nums.begin(),nums.end()); 28 } 29 } 30 };class Solution { 31 public: 32 void nextPermutation(vector<int>& nums) { 33 34 //1,2,3,4,6,5---> 1,2,3,(4) 6, (5)-swap--> 1,2,3,5,(6,4) -reverse-> 1,2,3,5,4,6 35 //先找出最大的索引 k 满足 nums[k] < nums[k+1],如果不存在,就翻转整个数组; 36 //再找出另一个最大索引 l 满足 nums[l] > nums[k]; 37 //交换 nums[l] 和 nums[k]; 38 //最后翻转 nums[k+1:]。 39 40 //先找出最大的索引 k 满足 nums[k] < nums[k+1],如果不存在,就翻转整个数组; 41 int i = nums.size()-2; 42 while(i>=0 && nums[i+1]<=nums[i]) { 43 i--; 44 } 45 //再找出另一个最大索引 l 满足 nums[l] > nums[k]; 46 int j = nums.size() -1; 47 if (i>=0) { 48 while(j >=0 && nums[j]<=nums[i]) { 49 j--; 50 } 51 //交换 nums[l] 和 nums[k]; 52 swap(nums[j],nums[i]); 53 //最后翻转 nums[k+1:]。 54 reverse(nums.begin()+i+1,nums.end()); 55 } else { 56 reverse(nums.begin(),nums.end()); 57 } 58 } 59 };
1 class Solution: 2 3 def nextPermutation(self, a): 4 """ 5 :type nums: List[int] 6 :rtype: void Do not return anything, modify nums in-place instead. 7 """ 8 def swap(a, i, j): 9 temp = a[i] 10 a[i] = a[j] 11 a[j] = temp 12 13 def reverces(a, i): 14 for k in range(int((len(a) - i) / 2)): 15 swap(a, i + k, len(a) - k - 1) 16 17 # 后找 18 i = len(a) - 2 19 while(i>=0 and a[i + 1] <= a[i]): 20 i -= 1 21 22 # 小大 23 if(i >= 0): 24 j = len(a) - 1 25 while j >= 0 and a[j] <= a[i]: 26 j -= 1 27 # 交换 28 swap(a, i, j) 29 # 反转 30 reverces(a, i+1)