47. Permutations II

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

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        if(!nums.size())
            return vector<vector<int> >();
        
        std::sort(nums.begin(),nums.end());
        bool visited[nums.size()] = {false};
        vector<vector<int> > res;
        vector<int> temp;
        permutation(temp, nums, visited, res);
        return res;
    }
    
    void permutation(vector<int> &temp, vector<int> &nums, bool visited[], vector<vector<int> > &res)
    {
        if(temp.size()==nums.size())
        {
            res.push_back(temp);
        }else
        {
            for(int i=0; i<nums.size(); i++)
            {
                if(i>0&&nums[i]==nums[i-1]&&!visited[i-1])
                    continue;
                if(!visited[i])
                {
                    visited[i] = true;
                    temp.push_back(nums[i]);
                    permutation(temp, nums, visited, res);
                    temp.pop_back();
                    visited[i] = false;
                }
                
            }
        }
    }
};


阅读更多
个人分类: LeetCode 排列组合
想对作者说点什么? 我来说一句

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

不良信息举报

47. Permutations II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭