leetcode 全排列系列

Next Permutation
 
AC Rate: 471/1794

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中也有next_permutation泛型算法,实现

细节大致如下:

在当前序列中从后往前找到第一对递增的pair,比如a[i]<a[i+1],那么i就叫做替换点,接着要从i之后的序列中从后往前找出第一个大于a[i]的数,

比如是a[i+k],那么将a[i]与a[i+k]交换,然后将a[i+1,...,len-1]这段序列做reverse即可

如果当前排列已经是最"大"的排列,比如"4321",那么全部reverse作为下一个排列。(此处描述参考http://blog.csdn.net/morewindows/article/details/7370155)

上代码

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        for(int i = num.size()-2; i >= 0; i --){
            if(num[i] < num[i+1]){
                for(int j = i + 1; j < num.size(); ++j){
                    if(j == num.size()-1 || num[j+1] <= num[i]){
                        swap(num[i],num[j]);
                        reverse(num.begin()+i+1,num.end());
                        return;
                    }
                }
            }
        }
        reverse(num.begin(),num.end());
        
    }
};

Permutations
 
AC Rate: 736/2366

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > ret;
        sort(num.begin(),num.end());
        do{
            ret.push_back(num);
        }while(nextPermute(num));
        return ret;
    }
    bool nextPermute(vector<int>& num)
    
        for(int i = num.size() - 2; i >= 0;  i--){
            if(num[i] < num[i+1]){
                for(int j = i + 1; j < num.size(); ++j){
                    if(j == num.size()-1 || num[j+1] <= num[i]){
                        swap(num[i],num[j]);
                        reverse(num.begin()+i+1,num.end());
                        return true;
                    }
                }
            }
        }
        reverse(num.begin(),num.end());
        return false;
    }
};

Permutations II
 
AC Rate: 519/1843

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       vector<vector<int> > ret;
       sort(num.begin(),num.end());
       do{
           ret.push_back(num);
       }while(nextPermute(num));
       return ret;
    }
    bool nextPermute(vector<int>& num){
        for(int i = num.size()-2; i >= 0; --i){
            if(num[i] < num[i+1]){
                for(int j = i +1 ; j < num.size(); ++j){
                    if(j == num.size()-1 || num[j+1] <= num[i]){
                        swap(num[i],num[j]);
                        reverse(num.begin()+i+1,num.end());
                        return true;
                    }
                    
                }
            }
        }
        reverse(num.begin(),num.end());
        return false;
        
    }
};
Permutation Sequence
 
AC Rate: 373/1865

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.


class Solution {
public:
    string getPermutation(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       /* my method
       if(1 == n) return "1";
        vector<bool> visit(n,false);
        string ret = "";
        int fact = 1;
        for(int i = 2; i <= n; ++i) fact *= i;
        int f = n;
        while(n != ret.length())
        {
            fact /= (f--);
           int pos = (k-1)/fact;
            int i = 0, j = 0;
            while( j < n )
            {
                if(!visit[j]){
                    ++i;
                    if(i == pos+1)
                        break;
                }
                ++j;
            }
            visit[j] = true;
            ret += (j + '1');
            k -= pos * fact;
        }
        return ret;*/
        
        //method from discuss forum,so clean and elegant
        vector<int> num(n);
        int i,q,d(1);
        for(i = 1; i <= n; ++i){
            d *= i;
            num[i-1] = i;
        }
        string ret;
        for(i = n; i >= 1; --i)
        {
            d /= i;
            q = (k-1)/d;
            k -= q * d;
            ret += ('0' + num[q]);
            num.erase(num.begin()+q);
        }
        return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值