31. Next Permutation

来源:互联网 发布:安卓和python 编辑:程序博客网 时间:2024/05/09 05:01

题意: 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

分析:找到数组最右侧的两个数nums[a],nums[b],使得nums[a] < nums[b],交换之,并从第a+1个数到数组尾部排序

AC代码:

class Solution {public:    void nextPermutation(vector<int>& nums) {        int a = 0, b = 0;        for(int i = 0; i < nums.size(); ++i){            for(int j = i; j < nums.size(); ++j){                if(nums[j] > nums[i]){                    a = i;                    b = j;                }            }        }        if(a == 0 && b == 0){            sort(nums.begin(), nums.end());            return;        }else{            int temp = nums[a];            nums[a] = nums[b];            nums[b] = temp;            sort(nums.begin() + a + 1, nums.end());        }    }};
0 0