leetcode_c++:Next Permutation (031)

题目

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

算法_1

STL的 next_pemutation

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

算法_2

输入: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
so,1 5 2 3 4 6 即为所求


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

        //找到第一个乱序列s
        while(idx >= 0 && nums[idx] >= nums[idx+1])
            idx--;

        //交换
         if(idx>=0)
         {
             int i=idx+1;
             while(i<nums.size() && nums[i]>nums[idx])
                 i++;
             swap(nums[i-1],nums[idx]);
         }

        // 反转
        reverse(nums.begin()+idx+1,nums.end());
        //全部是升序的情况,idx=-1
    }
};

你可能感兴趣的:(leetcode_c++:Next Permutation (031))