LeetCode 040. 组合总和 II 非SET去重

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

复制代码
给定一个数组 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 尝试每个数字是否要放入答案
注意 类似测试例子中 有多个1 的时候
注意避免出现多个1 ,2 ,5 的答案
这里规避的方案是 在DFS时候,如果不选择当前数字 则直接选择下一个不相同的数字

复制代码
class Solution {
public:
    vector<vector<int>> ans;

    void Dfs(vector<int> v, int curridx, const vector<int>& candidates, int target) 
    {
        if (curridx >= candidates.size())  return;
        if (candidates[curridx] > target) return;

        //当前数字不放进
        {
            //如果不选择 则选择与当前数字不同的数组
            int val = candidates[curridx];
            int idx = curridx;
            while (idx < candidates.size() && candidates[idx] == val) {
                idx++;
            }
            Dfs(v, idx, candidates, target);
        }

        //当前数字放进去
        {
            target = target - candidates[curridx];
            v.push_back(candidates[curridx]);
            if (target == 0) {
                ans.push_back(v);
                return;
            }
            Dfs(v, curridx + 1, candidates, target);
        }

    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        if (candidates.empty())  return ans;
        sort(candidates.begin(), candidates.end());
        int idx = 0;
        vector<int> v;
        Dfs(v, idx, candidates, target);

        return ans;
    }
};

 
复制代码

 

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

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

导航

< 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

统计

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