LeetCode算法题目:Next Permutation

来源:互联网 发布:多益网络校招登录 编辑:程序博客网 时间:2024/05/22 01:30

题目:

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


分析:

字典序法就是按照字典排序的思想逐一产生所有排列。
例如,由1,2,3,4组成的所有排列,从小到大的依次为:

1234, 1243, 1324, 1342, 1423, 1432,
2134, 2143, 2314, 2341, 2413, 2431,
3124, 3142, 3214, 3241, 3412, 3421,
4123, 4132, 4213, 4231, 4312, 4321.

分析这种过程,看后一个排列与前一个排列之间有什么关系?
再如,设有排列(p)=2763541,按照字典式排序,它的下一个排列是什么?
276 35 41 (找最后一个正序35)
27635 4 1 (找3后面比3大的最后一个数4)
276 4 5 3 1 (交换3,4的位置)
2764 135 (把4后面的5,3,1反转)
下面给出求 p[1…n] 的下一个排列的描述:

  1. 求 i = max{j | p[j – 1] < p[j]} (找最后一个正序)
  2. 求 j = max{k| p[i – 1] < p[k]} (找最后大于 p[i – 1] 的)
  3. 交换 p[i – 1] 与 p[j]得到 p[1] … p[i-2] p[j] p[i] p[i+1] … p[j-1] p[i-1] p[j+1] … p[n]
  4. 反转 p[j] 后面的数得到 p[1] … p[i-2] p[j] p[n] … p[j+1] p[i-1] p[j-1] … p[i]


代码:

class Solution {public:    void nextPermutation(vector<int>& nums) {        int i,j;        int length= nums.size();        for (i=length-2;i>=0;i--)        {            if(nums[i+1]>nums[i])            {                for(j=length-1;j>=0;j--)                {                    if(nums[j]>nums[i])                    break;                }                swap(nums[i],nums[j]);                reverse(nums.begin()+i+1,nums.end());                return;            }        }        reverse(nums.begin(),nums.end());        return;    }};
1 0
原创粉丝点击