permutation 系列

本文详细介绍了如何实现next permutation以及求解所有可能的permutations。对于有重复元素的情况,也给出了处理方法。同时,文章还讨论了如何找到给定索引k的第k个permutation序列的解题思路。
摘要由CSDN通过智能技术生成

关于permutation的讲解,请参见http://blog.csdn.net/xuqingict/article/details/24840183

[updated 2014.7.30]

所有的Permutation无论是否有重复元素,直接使用下面的代码即可,

bool helper(vector<int> &num)
{
    if(num.empty()) return false;
    typedef vector<int>::iterator iter;
    iter first=num.begin(), last=num.end();
    --last;
    if(first==last) return false;
    while(last != first && !(*(last-1) < *last))--last;  //此处直接使用!< 即可。。。
    if(last==first) return false;
    iter left=last-1,right=last;
    last=num.end();
    --last;
    while(!(*left < *last))--last;   //同上!!!
    iter_swap(left,last);
    reverse(right,num.end());
    return true;
}
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        if(num.empty()) return vector<vector<int> >();
        vector<vector<int> > ret;
        sort(num.begin(), num.end());
        do
        {
            ret.push_back(num);
        }while(helper(num));
        return ret;
    }


下列题目的讲解均是基于上面的文章:


题1: 

Next Permutation

  Total Accepted: 8066  Total Submissions: 32493 My Submissions

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值