Leetcode 40. 组合总和 II dfs

地址 https://leetcode-cn.com/problems/combination-sum-ii/submissions/

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

解法依旧是 DFS 问题在于每个元素最多只能选择一次
并且有重复的元素
这样带来的问题就是
AAB
如果选择第一个A不选择第二个A
和不选择第一个A选择第二个A 这样是重复的

其余和 39 组合总和 差不多

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> v;
    int sum;
    void dfs(vector<int>& candidates, int target,int idx)
    {
        if(sum == target){
            ans.push_back(v);return;
        }
        else if(idx>= candidates.size() || sum > target){return;}

        sum+=candidates[idx];  v.push_back(candidates[idx]);
        dfs(candidates,target,idx+1);
        v.pop_back(); sum-=candidates[idx];

        int i= idx;
        while(i<candidates.size() && candidates[i] == candidates[idx]) i++;
        if(i <candidates.size() )
            dfs(candidates,target,i);
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sum =0;
        sort(candidates.begin(),candidates.end());
        dfs(candidates,target,0);

        return ans;
    }
};

我的视频题解空间

posted on   itdef  阅读(125)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
历史上的今天:
2020-04-05 象棋博弈资源

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示