[leetcode]排列类问题

来源:互联网 发布:知乎和百度关系 编辑:程序博客网 时间:2024/06/06 06:52

31. Next Permutation

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,23,2,1 → 1,2,31,1,5 → 1,5,1

Algorithm from wikipedia:
Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
Find the largest index l greater than k such that a[k] < a[l].
Swap the value of a[k] with that of a[l].
Reverse the sequence from a[k + 1] up to and including the final element a[n].

void nextPermutation(vector<int>& nums){    int n = nums.size();    if (n <= 1)        return;    int i;    // get the rightmost that nums[i] < nums[i + 1]    for (i = nums.size() - 2; i >= 0 && nums[i] >= nums[i + 1]; --i);    if (i == -1)    {        reverse(nums.begin(), nums.end());        return;    }    int j;    // get the rightmost nums[j] that nums[j] > nums[i]    for (j = i + 1; j < nums.size() && nums[i] < nums[j]; ++j);    swap(nums[i], nums[--j]);    // reverse from i + 1 to the end    reverse(nums.begin() + i + 1, nums.end());}