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);
    }
}
相关推荐
弥彦_2 分钟前
cf1925B&C
数据结构·算法
YuTaoShao23 分钟前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14418 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录8 小时前
括号生成算法
前端·算法
渣呵9 小时前
求不重叠区间总和最大值
算法
拾光拾趣录9 小时前
链表合并:双指针与递归
前端·javascript·算法
好易学·数据结构9 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
香蕉可乐荷包蛋10 小时前
AI算法之图像识别与分类
人工智能·学习·算法
chuxinweihui11 小时前
stack,queue,priority_queue的模拟实现及常用接口
算法
tomato0911 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法