首页 > 其他分享 >40. 组合总和 II

40. 组合总和 II

时间:2022-11-10 13:22:24浏览次数:34  
标签:target int res 40 II depth vector candidates 总和

思路

为什么会出现重复?
以{1,1,7}和target = 8为例,
如果不选0号位置的1,那么1号位置的1就也不应该选
否则0号位置的1和7构成一个结果
在不选0号位置时,1号位置的1和7又构成一个结果
从而发生重复
所以去重的思路就是如果不选某个元素,那么之后和他相等的元素都应该跳过

代码

class Solution {
public:
    vector<vector<int>> ans;
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<int> res;
        dfs(candidates, res, 0, target);
        return ans;
    }

    void dfs(vector<int> &candidates, vector<int>& res, int depth, int target)
    {
        if(target == 0)
        {
            ans.push_back(res);
            return;   
        }
        if(depth == candidates.size() || target < candidates[depth]) return;

        int val = candidates[depth];

        // not choose
        for(int j = depth + 1; j < candidates.size(); j++)
            if(candidates[j] != candidates[depth])
            {
                dfs(candidates, res, j, target);
                break;
            }

        // choose 
        res.push_back(val);
        dfs(candidates, res, depth + 1, target - val);
        res.pop_back();
    }
};

标签:target,int,res,40,II,depth,vector,candidates,总和
From: https://www.cnblogs.com/INnoVationv2/p/16876733.html

相关文章

  • HDU 2216 Game III
    ProblemDescriptionZjtandSarawilltakepartinagame,namedGameIII.ZjtandSarawillbeinamaze,andZjtmustfindSara.Therearesomestrang......
  • The 2022 ICPC Asia Regionals Online Contest (II)
    一直没补,把之前的粘贴过来EAnInterestingSequence 为使数组和小,并且gcd=1,我们添加2,3,,找到第一个不整除k的质数,然后后面放2,3,判断先放2还是3JAGameaboutIncrea......
  • 454. 四数相加 II
    454.四数相加II给你四个整数数组nums1、nums2、nums3和nums4,数组长度都是n,请你计算有多少个元组(i,j,k,l)能满足:0<=i,j,k,l<nnums1[i]+nums2......
  • POJ 2407 Relatives
    DescriptionGivenn,apositiveinteger,howmanypositiveintegerslessthannarerelativelyprimeton?Twointegersaandbarerelativelyprimeifth......
  • 关于异常DBG_TERMINATE_PROCESS(0x40010004)
    简介DBG_TERMINATE_PROCESS表示进程被调试器终止。值为0x40010004。其定义如下:////MessageId:DBG_TERMINATE_PROCESS////MessageText:////Debuggerterminatedproce......
  • HDU 5402 Travelling Salesman Problem
    ProblemDescriptionn rowsand m columns.Thereisanon-negativenumberineachcell.TeacherMaiwantstowalkfromthetopleftcorner (1,1......
  • 【408】2020
    t5问的是二叉排序树,没问二叉平衡树=.=t11稳定的排序算法:直接插入、冒泡、2归并、基数排序空间复杂度:快速排序:借助栈,空间复杂度一般是O(logn),但在最坏情况下会增......
  • 代码随想录day50 | 123.买卖股票的最佳时机III 188. 买卖股票的最佳时机 IV
    123.买卖股票的最佳时机III题目|文章思路相比于122.买卖股票的最佳时机III,这道题多了一道限制,就是买卖次数的限制,我的想法是通过增加一维来实现。文章中给出的方法则......
  • HDU 4041 Eliminate Witches!
    ProblemDescriptionKanameMadokaisaMagicalGirl(MahouShoujo/PuellaMagi).ThedutyofaMagicalGirlistoeliminateWitches(Majo).Thoughsoundshorrif......
  • SPOJ LCS2 Longest Common Substring II
    DescriptionAstringisfinitesequenceofcharactersoveranon-emptyfinitesetΣ.Inthisproblem,Σisthesetoflowercaseletters.Substring,alsocalled......