31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code

The replacement must be in-place, do not allocate extra memory.blog

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,1it

void nextPermutation(vector<int>& nums) {
    int n = nums.size(), i, j;
    for(i = n-2; i >= 0; i--)
    {
        if(nums[i+1] > nums[i])
        {
            reverse(nums.begin()+i+1, nums.end()); //或sort
            for(j = i+1; j < n; j++)
            {
                if(nums[j] > nums[i])
                {
                    nums[i] = nums[i] ^ nums[j];
                    nums[j] = nums[i] ^ nums[j];
                    nums[i] = nums[i] ^ nums[j];
                    break;
                }
            }
            return;
        }
    }
    if(i < 0)
        reverse(nums.begin(), nums.end()); //或sort
}
相關文章
相關標籤/搜索