Leetcode -- 31. Next Permutation

来源:互联网 发布:java实战项目百度云 编辑:程序博客网 时间:2024/06/05 17: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


思路:这道题还是有点难度的,参考了别人的思路,解法如下:

6,8,7,4,3,2为例:
这里写图片描述

  1. 首先从后往前遍历,找到第一个不按递增排列的元素,即nums[i-1],上图中的6。
  2. 再从后往前,找到第一个比nums[i-1] 大的元素,即nums[j] , 上图中的7。
  3. 交换nums[i-1]nums[j] 的位置,变成7, 8, 6, 4, 3, 2
  4. i → nums.size()-1 的元素进行排序, 变成:7, 2, 3, 4, 6, 8

C++代码如下:

void nextPermutation(vector<int>& nums) {        if (nums.size() <= 1)            return;        int right = nums.size() - 1;        int i = right,j = right,temp;        while (nums[i] <= nums[i - 1]) {            --i;        }        if (i == 0) {            sort(nums.begin(), nums.end());            return;        }        while (nums[i-1] >= nums[j])        {            --j;        }        temp = nums[j];        nums[j] = nums[i-1];        nums[i-1] = temp;        sort(nums.begin() + i,nums.end());}
0 0