leetcode31 - Next Permutation - medium
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,23,2,1 → 1,2,31,1,5 → 1,5,1
这道题的关键是要找到从哪个点去backtrack(只是突破口,和backtrack也没关系)。思考permutations里我们是如何对每个slot进行填数的:假设nums是递增的,填当前slot的时候从头开始挨个遍历nums,也就是说[1,2,3]我们填到1,3,x的这个3的时候,它已经是这个slot能填的最大的数了,不应该去替换它。Generalize一下,从后往前找,任何strictly decreasing section都没啥能动的了,找到第一对nums[pos]<nums[pos+1]的对子,这个pos就是我们要修改的slot。再从pos之后找个比它大的数和它换,最后保证pos之后是sorted的以满足答案是最小的。
一开始标记一下pos=-1,扫一遍pos还是-1说明不存在,直接重排整个数组。排序的时候reverse复杂度好于sort。
实现:
class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(); if (n <= 1) return; int pos = -1; for (int i=n-2; i>=0; i--){ if (nums[i] < nums[i+1]){ pos = i; break; } } if (pos == -1) return reverse(nums.begin(), nums.end()); else{ int j = n-1; while (j > pos && nums[pos] >= nums[j]) j--; swap(nums[pos], nums[j]); reverse(nums.begin()+pos+1, nums.end()); } } };

浙公网安备 33010602011771号