数组(11):下一个排列

描述:
31. Next Permutation
Total Accepted: 54346 Total Submissions: 212155 Difficulty: Medium
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

STL来做,秒杀

[html] view plain copy
class Solution {  
public:  
    void nextPermutation(vector<int>& nums) {  
        next_permutation(nums.begin(), nums.end());  
    }  
};  

此题感觉没多大意思,不好快速想出规律:

但是比较明显的规律是:

1,升序为最小组合,降序为最大组合

2,某一个数的下一个数,就是比他大的最小组合数,比如123,下一个比他大的最小组合就是132,必须从低位处理

3,stl的处理就是从低位(数组末尾)开始找起,

a)找到首个相邻的升序序列,将前一个数据与比其首次大的数交换(然后逆置后面的数)比如:123543为124533(首个升序3,5,但是4是首次比3大,则交换),此处的操作意义就是使数通过首个升序变大。

b)显然此数不是大于原数的最小数,并且后面的数逆置后才是最小的,即124533为124335。so,done!。

[cpp] view plain copy
//思路首先(不调用库函数):  
//举例:abc,acb,bac,bca,cab,cba  
class Solution {  
public:  
    void nextPermutation(vector<int>& nums) {  
        if(nums.empty() || nums.size()==1)  
            return;  
        vector<int>::iterator ite1=nums.end();  
        ite1--;  
        while(true)  
        {  
            vector<int>::iterator ite2=ite1;  
            ite1--;//ite1始终在ite2前面一个位置(左边算作最前面)  
            if(*ite1 < *ite2)//升序已经出现,接着重新从后面找首个升序位置  
            {  
                vector<int>::iterator itej=nums.end();  
                while(!(*ite1 < *--itej));  
                iter_swap(ite1,itej);//找到首个升序序列将其交换  
                reverse(ite2,nums.end());  
                return;  
            }  

            if(ite1==nums.begin())  
            {   
               reverse(nums.begin(),nums.end());  
               return;  
            }  
        }  
    }  
};  

注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50450861
原作者博客:http://blog.csdn.net/ebowtang

猜你喜欢

转载自blog.csdn.net/rOokieMonkey/article/details/80241732