40.组合综合Ⅱ

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

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

**注意:**解集不能包含重复的组合。

java 复制代码
List<List<Integer>> res = new ArrayList<>();

List<Integer> temp = new ArrayList<>();

public List<List<Integer>> combinationSum(int[] candidates, int target){
    Arrays.sort(candidates);
    backtrace(candidates, target, 0);
    return res;
}

public void backtrace(int[] candidates, int target, int idx){
    if(target < 0) return;
    if(target == 0){
        if(!res.contains(temp)) res.add(new ArrayList(temp));
        return;
    }
    if(idx < candidates.length && candidate[idx] > target) return;
    for(int i = idx; i < candidates.length; i++){
        // 这句代码防止candidates数组全是相同数字引起的超时问题
        if(i > 0 && candidates[i] == candidates[i-1]) continue;
        temp.add(candidates[i]);
        backtrace(candidates, target - candidates[i], i + 1);
        temp.remove(temp.size() - 1);
    }
}
相关推荐
无敌最俊朗@19 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^19 小时前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
夏鹏今天学习了吗19 小时前
【LeetCode热题100(66/100)】寻找两个正序数组的中位数
算法·leetcode·职场和发展
墨染点香19 小时前
LeetCode 刷题【151. 反转字符串中的单词】
算法·leetcode·职场和发展
ytttr87319 小时前
Landweber迭代算法用于一维、二维图像重建
人工智能·算法·机器学习
feifeigo12320 小时前
Matlab编写压缩感知重建算法集
人工智能·算法·matlab
烛衔溟20 小时前
C语言多级指针与函数指针:指针的高级用法
c语言·算法
Sunhen_Qiletian21 小时前
YOLOv2算法详解(下篇):细节打磨与性能突破的终极密码
算法·yolo
wefg11 天前
【数据结构】unordered 系列容器底层结构和封装
数据结构·算法·哈希算法