您的位置:首页 > 其它

【LeetCode】31. Next Permutation

2018-04-09 22:58 357 查看

题目描述

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


解题思路

因为要找的是比当前排列大一点的下一个排列,所以应该通过调整最靠后面的数字的排序来实现。

从后往前找,如果数字一直增大,那是没有办法通过调整后面的排列来得到更大的排列的。

当找到一个数字,它比后一个数字小时,才可以开始实行交换。将那个数字与已经遍历过的部分中恰好比它大一点的值进行交换,然后反转后半部分,即让它由从后往前的递增变为递减。

AC代码

class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() < 2)
return;

int startIdx = nums.size() - 2;
while (startIdx >= 0) {
if (nums[startIdx] >= nums[startIdx + 1]) {
startIdx--;
}
else {
//get the upper bound
int upperIdx = nums.size() - 1;
for (; upperIdx > startIdx; --upperIdx) {
if (nums[upperIdx] > nums[startIdx])
break;
}
//swap and break
int temp = nums[startIdx];
nums[startIdx] = nums[upperIdx];
nums[upperIdx] = temp;
break;
}
}
sort(nums.begin() + startIdx + 1, nums.end());
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode