31. Next Permutation

来源:互联网 发布:财神软件 编辑:程序博客网 时间:2024/06/06 19:14

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

这题属于找规律题,不需要运用典型算法,就是理清楚下一个permutation的出现遵循什么规律。主要是三步:
1. 从右往左找到第一个比右边小的数,即nums[i] < nums[i + 1];
2. 然后在i 的右侧找最小的比nums[i]大的数nums[j];
3. 交换i 和 j 然后对i 右侧数组重新sorting。

代码:

void nextPermutation(vector<int>& nums) {    int len = nums.size();    if (len <= 1) return;    int i;    for (i = len - 2; i >= 0; i--) {        if (nums[i] < nums[i + 1]) break;    }    if (i < 0) {        sort(nums.begin(), nums.end());        return;    }    int pos = i;    int next = i + 1;    for (i = pos + 1; i < len; i++) {        if (nums[i] < nums[next] && nums[i] > nums[pos]) next = i;      }    int temp = nums[pos];    nums[pos] = nums[next];    nums[next] = temp;    sort(nums.begin() + pos + 1, nums.end());}
原创粉丝点击