• 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;
        }
    };
    
     
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    labview dll 崩溃
    java方法01什么是方法?
    java控制流程控制10增强For循环
    Java方法05可变参数
    java流程控制09打印九九乘法表
    Java流程控制12打印三角形及DUG
    Java方法02方法的定义和调用
    Java流程控制08For循环详解
    java流程控制11break、continue、goto
    java方法04命令行传递参数
  • 原文地址:https://www.cnblogs.com/itdef/p/14072365.html
Copyright © 2020-2023  润新知