Next Permutation

来源:互联网 发布:ecshop 2.0数据字典 编辑:程序博客网 时间:2024/06/05 21:53

题目描述:
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

分析:
我们只需要找到第一个可以和之前为交换变大的数,然后将其以之前比他大而且最小的交换,然后将之前的树从小到大排序即可

代码如下:

 void nextPermutation(vector<int>& nums) {      if(nums.size()==1) return;        int map[1000]={0};        int ok=0;        int kk;        for(int i=nums.size()-1;i>0;i--){            map[nums[i]]++;            if(nums[i]>nums[i-1]){                map[nums[i-1]]++;                int min=100000;                int flag=-1;                for(int j=i-1;j<nums.size();j++){                    if(nums[j]<=min&&nums[j]>nums[i-1]&&j>flag){                        min=nums[j];                        flag=j;                    }                }                int temp=nums[flag];                nums[flag]=nums[i-1];                nums[i-1]=temp;                map[temp]--;                ok=1;                kk=i;                break;            }        }        if(ok){            int len=nums.size();        for(int j=kk;j<len;j++) nums.pop_back();            for(int i=0;i<1000;i++){                while(map[i]--){                    nums.push_back(i);                }            }        }        if(!ok)        map[nums[0]]++;        if(!ok){            nums.clear();            for(int i=0;i<1000;i++){                while(map[i]--){                    nums.push_back(i);                }            }        }    }
原创粉丝点击