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);
    }
}
相关推荐
可编程芯片开发1 小时前
基于霍尔传感器和PID控制器的有功功率检测控制系统simulink建模与仿真
算法
To_OC1 小时前
LC 17 电话号码的字母组合:我的回溯算法,就是从这道题开窍的
javascript·算法·leetcode
战族狼魂4 小时前
GPT-5.6与Grok 4.5重磅发布
人工智能·算法·大模型·大语言模型
白日焰火14 小时前
基于 OpenSpec 实现规范驱动开发
算法·交互
imuliuliang5 小时前
关于图搜索算法的性能建模与可预测性研究7
算法
ForDreamMusk6 小时前
批量归一化
人工智能·算法·机器学习
Ivanqhz7 小时前
刚体的自由度
人工智能·算法
KaMeidebaby7 小时前
卡梅德生物技术快报|抗体合成:多肽抗体合成工程化方案:Nsp2 保守肽多抗制备与多维度验证
前端·网络·数据库·人工智能·算法
Yang_jie_038 小时前
笔记:数据结构(栈是否使用底指针以及头指针的初始化值)
数据结构·笔记·算法
2301_800895108 小时前
信息安全数学基础复习
算法