<LeetCode OJ> 31. Next Permutation

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来做,秒杀

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!。

//思路首先(不调用库函数):
//举例: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



参考资源

【1】侯捷,《STL源码剥析》

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值