<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">问题描述:</span>
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
问题分析:
题目的意思是:123的全排列按字典顺序为:
123 132 213 231 312 321
如果输入其中某一个序列,返回它的下一个序列。如:输入:213 输出:231 ;输入:321 输出:123
算法思想:举例如下
输入:1 4 6 5 3 2
step1:从右往左找到第一个破坏升序(非严格)的元素,此例中为4.记下标为 i
step2: 依然从右往左,找到第一个大于4的元素,此例中5,交换4和5.
step3:从i+1到最右端,逆置。6 4 3 2 to 2 3 4 6
问题求解一:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(!nums.size())
return;
// find the last wrong number
int idx = nums.size()-2;
while(idx >= 0 &&nums[idx] >= nums[idx+1])
idx--;
// swap the number
if(idx >= 0){
int i = idx + 1;
while(i < nums.size() && nums[i] > nums[idx])
i++;
swap(nums[i-1], nums[idx]);
}
// reverse
reverse(nums.begin() + idx + 1, nums.end());
}
};
问题求解二:
使用C++ STL标准库函数next_permutation()
class Solution {
public:
void nextPermutation(vector<int> &num) {
next_permutation(num.begin(), num.end());
}
};