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
解题思路
若把 n 个整数的所有全排列按升序排好序,则 nextPermutation 函数应返回当前排列在该升序下的下一个排列。
对当前排列从后向前扫描,找到第一对为升序的相邻元素,记为
- 如果不存在这样一对为升序的相邻元素,则当前排列为降序,按题意应返回升序的排列;
- 否则,对当前排列从后向前扫描,找到第一个大于 i 的元素
k ,交换 i 和 k,然后对从i+1 开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。
代码如下:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int size = nums.size();
if (size < 2) return;
int i, k;
// 从后向前找到第一对为升序的相邻元素,nums[i] < nums[i+1]
for (i = size - 2; i >= 0; --i) {
if (nums[i+1] > nums[i]) break;
}
// 存在这样一对为升序的相邻元素
if (i >= 0) {
// 从后向前找到第一个大于 nums[i] 的元素 nums[k]
for (k = size - 1; k > i; --k) {
if (nums[k] > nums[i]) break;
}
swap(nums[i], nums[k]); // 交换 nums[i] 和 nums[k] 的值
}
// 反转
reverse(nums.begin() + i + 1, nums.end());
}
};
本文介绍了一种实现NextPermutation的算法,该算法用于寻找给定整数序列的下一个字典序排列。通过从后向前查找升序对,并进行元素交换及子序列反转操作,实现在原地替换为下一个更大的排列。

被折叠的 条评论
为什么被折叠?



