xinyu04

导航

LeetCode 47 Permutations II 可重集全排列

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

Solution

对于有重复元素的全排列,我们用 \(set\) 来记录当前位置被哪些元素给替换了,这里直接用 \(swap\) 交换即可,如果当前位置到达末尾时,加入答案即可

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
    
    void dfs(vector<int>& nums, int pos){
        if(pos==nums.size()){
            ans.push_back(nums); return;
        }
        
        set<int> vis;
        for(int i=pos;i<nums.size();i++){
            if(vis.count(nums[i]))continue;
            vis.insert(nums[i]);
            swap(nums[pos], nums[i]);
            dfs(nums, pos+1);
            swap(nums[pos], nums[i]);
        }
        
    }
    
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        dfs(nums, 0);
        return ans;
    }
};

posted on 2022-08-07 17:28  Blackzxy  阅读(15)  评论(0编辑  收藏  举报