31. Next Permutation

来源:互联网 发布:c#foreach遍历数组 编辑:程序博客网 时间:2024/06/10 22:56

题目

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

分析

寻找当前排列的下一个排列,即所有排列看做数字,下一个排列的值是第一个比当前排列值大的排列,具体算法参考:A simple algorithm from Wikipedia with C++ implementation (can be used in Permutations and Permutations II)

注:可以用sort代替reverse做翻转。

class Solution {public:    void nextPermutation(vector<int>& nums) {        int k=-1;        int size=nums.size();        for(int i=0;i<size-1;++i){//先顺序查找最大的下标k使得nums[k]<nums[k+1]            if(nums[i]<nums[i+1])                k=i;        }        if(k==-1){//如果没有则整体翻转            sort(nums.begin(),nums.end());            return ;        }        int j=-1;        for(int i=size-1;i>k;--i){//找到k之后的最大下标使得nums[k]<nums[j]            if(nums[k]<nums[i]){                j=i;                break;            }        }        swap(nums[k],nums[j]);//交换后翻转k+1到end的部分        sort(nums.begin()+k+1,nums.end());            }};


原创粉丝点击