LeetCode 90 Subsets II 回溯


Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Solution

如何处理相同的子集:先把 /(vector/) /(sort/) 一下,然后在 /(ans/) 里面 /(find/), 依旧记得擦除标记

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
    vector<int> res;
    
    
    void dfs(vector<int> nums, vector<int>&res, int pos){
        
        for(int i=pos; i<nums.size();i++){
            res.push_back(nums[i]);
            
            vector<int> tmp = res;
            
            sort(res.begin(), res.end());
            if(find(ans.begin(), ans.end(), res) == ans.end()){
                // not repeated
                ans.push_back(res);
            }
            dfs(nums, res, i+1);
            res = tmp;
            res.pop_back();
        }
    }
    
    
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        ans.push_back(res);
        dfs(nums, res, 0);
        return ans;
    }
};

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279305.html

(0)
上一篇 2022年8月7日
下一篇 2022年8月7日

相关推荐

发表回复

登录后才能评论