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);
    }
}
相关推荐
天一生水water18 分钟前
基于FFT的频域故障诊断
人工智能·算法·智慧油田
石去皿28 分钟前
数据结构与算法面试核心考点精要
java·算法·面试
今儿敲了吗32 分钟前
18| 差分数组
c++·笔记·学习·算法
Bear on Toilet44 分钟前
BFS_FloodFill_46 . 腐烂的橘子问题
数据结构·c++·算法·leetcode·宽度优先
大模型玩家七七1 小时前
关系记忆不是越完整越好:chunk size 的隐性代价
java·前端·数据库·人工智能·深度学习·算法·oracle
样例过了就是过了1 小时前
LeetCode热题100 找到字符串中所有字母异位词
算法·leetcode
DevilSeagull1 小时前
C语言: C语言内存函数详解
c语言·开发语言·算法
搞科研的小刘选手1 小时前
【人工智能专题】2026年人工智能与生成式设计国际学术会议(ICAIGD 2026)
人工智能·算法·aigc·生成式ai·学术会议·计算机工程·生成式设计
stripe-python1 小时前
十二重铲雪法(上)
c++·算法
ccLianLian2 小时前
计算机基础·cs336·RLHF
深度学习·算法