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);
    }
}
相关推荐
黄金龙PLUS8 分钟前
5个800比特大状态置换算法的设计与分析
算法·网络安全·密码学·哈希算法·同态加密
政企项目老覃19 分钟前
大模型 Agent 自主任务编排:电商客服地址解析从 12% 失败率到 2.1% 的落地复盘
人工智能·程序人生·算法
kukubuzai34 分钟前
双指针系列二--末尾篇(3道题)
c++·算法·leetcode
杜 硕1 小时前
单链表经典算法题
数据结构·算法
小O的算法实验室1 小时前
IEEE TCYB,着色旅行商问题:模型、求解与应用
算法
h_a_o777oah1 小时前
【图论】网络流:Dinic 算法模板实现原理及解题技巧
c++·算法·图论·acm·网络流·最小割·dinic算法
我不会起名字3222 小时前
一天一道力扣Hot100(37):深度优先算法--括号生成
java·数据结构·c++·后端·python·算法·go
foolishlee2 小时前
SCRAM-SHA-256
数据库·算法·postgresql
Rabitebla2 小时前
【Linux 系统编程】权限(一):身份、提权,和那 9 个权限位
linux·数据结构·c++·算法
-dzk-2 小时前
【回溯】LC 22.括号生成
算法·回溯