【LeetCode】31. Next Permutation (2 solutions)

时间:2022-06-07 16:45:39

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

解法一:just a joke :)

class Solution {
public:
void nextPermutation(vector<int> &num) {
next_permutation(num.begin(), num.end());
}
};

【LeetCode】31. Next Permutation (2 solutions)

解法二:

1、如果数组为降序,则根据题意,升序排序后返回。

2、如果数组为升序,则交换最后两个元素后返回。

3、举例来说明:

[1,2,5,4,3]-->[1,3,2,4,5]

从右往左递增的序列是不改动的。因为递增已经是最大。

因此要改动的就是递增部分的断点。

如上例,5,4,3是不可能改动的,越改越小,与“下一个序列”的定义不符。

因此要改动的就是2.

需要将2的位置替换为3,也就是从右往左比2大的数中最小的那个数,也就是3。如果不是选最小,那就会跳过很多排列。

将3放到2的位置,新排列的头部为[1,3]。

由于3第一次出现在第二个位置,因此其余数组应该呈最小序,也就是将[5,4,2]排序。

最终结果为[1,3,2,4,5]

class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.empty())
return;
int size = nums.size();
int ind = size-;
while(ind > && nums[ind] <= nums[ind-])
ind --;
if(ind == )
{// descend
sort(nums.begin(), nums.end());
}
else if(ind == size-)
{// ascend
// swap the last two element
swap(nums[ind], nums[ind-]);
}
else
{
int ind2 = size-;
while(nums[ind-] >= nums[ind2])
ind2 --;
// nums[ind-1] < nums[ind2]
swap(nums[ind-], nums[ind2]);
sort(nums.begin()+ind, nums.end());
}
}
};

【LeetCode】31. Next Permutation (2 solutions)