您的位置:首页 > 编程语言 > C语言/C++

LeetCode刷题(C++)——Next Permutation(Medium)

2017-05-09 20:54 309 查看
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


思路:C++的STL中有一个next_permutation的函数,函数功能是生成当前排列的下一个排列,此处就是让我们自己实现这个next_permutation
其实实现这个函数功能不难,主要是我们需要先了解这个函数是如何得到下一个排列的,举个例子:对于[1,3,6,5,4,2]这个排列,它的下一个排列为[1,4,2,3,5,6],这个是怎么得到的呢???
(1)从都往前遍历,如果后一个数比前一个数大,继续往前寻找,直到找到第一个不是依次增长的数,记录该数位置为i;
(2)此时对应两种情况:
一是该序列为递增序列,即元素从后往前都是递增的,说明这个序列为最后一个排列,那么下一个序列为第一个排列,把所有元素翻转即可,如{4,3,2,1}->{1,2,3,4};
二是如果找到的存在且 i>0,那么此时从i+1开始往后遍历,寻找第一个比i位置上的数小的数,记录它的位置为j,此时交换第i和第j-1位置的数,然后将i位置以后的所有数进行翻转,就是我们要的下一个排列。
代码如下:

class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() < 2)
return;
int i=nums.size()-1;
while (i > 0 && nums[i] <= nums[i - 1])
i--;
i--;
if (i >= 0) {
int j = i + 1;
while (j<nums.size() && nums[j]>nums[i])
j++;
j--;
swap(nums[i], nums[j]);
}
reverse(nums, i + 1, nums.size() - 1);
}

void reverse(vector<int>& nums, int i, int j)
{
if (i > j)
return;
while (i < j)
swap(nums[i++], nums[j--]);
}
};



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息