力扣 40组合总和 II

和昨天差不多

一种暴力去重  昨天方法对结果set

一种中间去重

力扣 40组合总和 II_第1张图片

暴力去重是直接算出结果后用set insert

class Solution {
public:
    vector> combinationSum2(vector& candidates, int target) {
        vector>res;
        sort(candidates.begin(),candidates.end());
        if(candidates.size() == 0 || candidates[0] > target)
        {
            return res;
        }
        vectortmp;
        dfs(candidates,target,0,0,tmp,res);
        set> s;
        for(auto c : res)
        {
            s.insert(c);
        }
        vector>ans;
        for(auto c : s)
        {
            ans.push_back(c);
        }
        return ans;
    }
    void dfs(vector& candidates, int target, int start, int sum, vector& tmp, vector>& res)
    {
        if(sum == target)
        {
            res.push_back(tmp);
            return;
        }
        if(sum > target)
        {
            sum -= tmp[tmp.size()-1];
            //tmp.pop_back();
            return;
        }
        for(int i = start; i < candidates.size(); i++)
        {
            if(i > start && candidates[i] == candidates[i-1])
            {
               // continue;
            }
            tmp.push_back(candidates[i]);
            dfs(candidates,target,i+1,sum + candidates[i],tmp,res);
            tmp.pop_back();
        }

    }
};

力扣 40组合总和 II_第2张图片

class Solution {
public:
    vector> combinationSum2(vector& candidates, int target) {
        vector>res;
        sort(candidates.begin(),candidates.end());
        if(candidates.size() == 0 || candidates[0] > target)
        {
            return res;
        }
        vectortmp;
        dfs(candidates,target,0,0,tmp,res);
        // set> s;
        // for(auto c : res)
        // {
        //     s.insert(c);
        // }
        // vector>ans;
        // for(auto c : s)
        // {
        //     ans.push_back(c);
        // }
        return res;
    }
    void dfs(vector& candidates, int target, int start, int sum, vector& tmp, vector>& res)
    {
        if(sum == target)
        {
            res.push_back(tmp);
            return;
        }
        if(sum > target)
        {
            sum -= tmp[tmp.size()-1];
            //tmp.pop_back();
            return;
        }
        for(int i = start; i < candidates.size(); i++)
        {
            if(i > start && candidates[i] == candidates[i-1])
            {
                continue;
            }
            tmp.push_back(candidates[i]);
            dfs(candidates,target,i+1,sum + candidates[i],tmp,res);
            tmp.pop_back();
        }

    }
};

力扣 40组合总和 II_第3张图片

你可能感兴趣的:(#,回溯)