31-NextPermutation

来源:互联网 发布:mysql front 编辑:程序博客网 时间:2024/06/05 03:22
题目:

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

分析:

这个题目是一组数字进行全排列,然后找到其中一个序列的下一个序列
NextPermutation 序列所组成的数字比上一个大,一个逆序排列的数组没有下一个排列。
主要是两个Flag

  • step 1. 从右向左找到第一个比i+1 位置的数字小的i
  • step 2. 从右向左找到第一个比nums[i] 大的数字nums[j](这里我采用的是从左向右)
  • step 3. swap(nums,i,j)
  • step 4. 将i+1 ~end 的数字进行逆序
代码:
class Solution {public:    void nextPermutation(vector<int>& nums) {        int len = nums.size();        int i = len - 2;        while ((i >= 0) && (nums[i] >= nums[i + 1]))        {            i--;        }        int j = i+1;        if (i >= 0)        {            while (j < len&&nums[j]>nums[i])            {                j++;            }            swap(nums, i, j-1);        }        reverse(nums, i + 1);    }    void reverse(vector<int>& nums, int start)    {        int end = nums.size()-1;        while (start < end)        {            swap(nums, start, end);            start++;            end--;        }    }    void swap(vector<int>& nums, int i, int j)    {        int tmp = 0;        tmp = nums[i];        nums[i] = nums[j];        nums[j] = tmp;    }};
原创粉丝点击