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
LeetCode里面有很多关于Permutation的题目,在这个系列当中有和回溯挂钩的求所有Permutation的题目,分为包含重复和不包含重复的两种,之前已经写过关于这两题的总结。这道题和LC 60 Permutation Sequence更像,相比那道题,这道求Next Permutation的题目要更简单一点。
思路是这样,从给定的数组最右侧向左侧遍历,寻找一个number and its index where the ascending sequence is interrupted. 例如给一个数组 [6, 5, 1, 4, 3, 2],从最右侧的 2 开始向前看,直到找到打断上升的那个数字,这里就是 num[2] = 1。 观察从它开始的子串,即 [1, 4, 3, 2],第一个数往后的所有数(4,3,2)都是有序的递减的,而递减的子串已经是所有permutation当中的最后一个,所以这时必须从递减的里面找出一个最小的数放在原来 1 的位置上,这样就变成了[2, 4, 3, 1]。还没有结束,此时开始了一个新的排序,2的位置就是它在next permutation中应该在的位置,但是作为新的permutation的开始,它后面的数组应该变成有序递增。代码:
void nextPermutation(vector<int>& nums) {
int i, j;
i = j = (int)nums.size() - 1;
// iterate from right to left, see where breaks the ascending order.
while (i > 0 && nums[i-1] >= nums[i]) {
i--;
}
if (i == 0) {
// already the biggest permuatation, no next exists. arrange it to ascending order.
sort(nums.begin(), nums.end());
return;
}
i--;
while (i < j && nums[j] <= nums[i]) {
j--;
}
// on right side of nums[i] exists smallest nums[j] but bigger than nums[i].
swap(nums[i], nums[j]);
// nums on right side of nums[i] just need to be sorted by ascending order.
sort(nums.begin() + i + 1, nums.end());
}
需要注意的是,当数组已经是整个递减的情况,说明已经不存在有效的next permutation,因此需要特别处理,即sort()。