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+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 &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 > permute(vector &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector > ret;
        sort(num.begin(),num.end());
        do{
            ret.push_back(num);
        }while(nextPermute(num));
        return ret;
    }
    bool nextPermute(vector& 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 > permuteUnique(vector &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       vector > ret;
       sort(num.begin(),num.end());
       do{
           ret.push_back(num);
       }while(nextPermute(num));
       return ret;
    }
    bool nextPermute(vector& 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 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 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;
    }
};


你可能感兴趣的:(leetcode)