leetcode 47 : Permutations II

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 {
    vector > ret;
    int N;
    
public:
    void perm(vector &nums, int i){
        if( i == N){
            ret.push_back(nums);
        }
        set setNums;
        for(int j = i; j < N; j++){
            //没有交换过的元素才交换
            if( setNums.find(nums[j])==setNums.end() )
            {
                setNums.insert(nums[j]);
                swap(nums[i], nums[j]);
                perm(nums, i + 1);
                swap(nums[j], nums[i]);
            }
        }
    }

    vector> permuteUnique(vector& nums) {
        N = nums.size();
        ret.clear();
        perm(nums, 0);
        return ret;
    }
};
//next_permute
class Solution {
public:
    //不循环
    bool next_permute(vector& nums){
        if(nums.size()==0||nums.size()==1)
            return false;
        vector::iterator itF=nums.end()-2;
        vector::iterator itS=nums.end()-1;
        while(true)
        {
            if(*itF<*itS)
            {    
                vector::iterator tmpIt = nums.end()-1;
                while(*tmpIt<=*itF)
                    tmpIt--;
                int tmp=*itF;
                *itF=*tmpIt;
                *tmpIt=tmp;
                break;
            }
            if(itF==nums.begin())
            {
                return false;
            }
            itF--;
            itS--;
        }
        reverse(itS,nums.end());
        return true;
    }
    vector> permuteUnique(vector& nums) {
        vector> ret;
        sort(nums.begin(),nums.end());
        ret.push_back(nums);
        while(next_permute(nums))
            ret.push_back(nums);
        return ret;
    }
};
阅读更多
文章标签: 算法 面试 leetcode
个人分类: 算法 c++ c
上一篇leetcode 46 : Permutations
下一篇leetcode 53: Maximum Subarray
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭