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);
    }
}
相关推荐
凌肖战6 分钟前
力扣上刷题之C语言实现(数组)
c语言·算法·leetcode
秋夫人33 分钟前
B+树(B+TREE)索引
数据结构·算法
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
Milo_K1 小时前
今日 leetCode 15.三数之和
算法·leetcode
Darling_001 小时前
LeetCode_sql_day28(1767.寻找没有被执行的任务对)
sql·算法·leetcode
AlexMercer10121 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
Greyplayground1 小时前
【算法基础实验】图论-BellmanFord最短路径
算法·图论·最短路径
蓑 羽1 小时前
力扣438 找到字符串中所有字母异位词 Java版本
java·算法·leetcode
源代码:趴菜1 小时前
LeetCode63:不同路径II
算法·leetcode·职场和发展
儿创社ErChaungClub2 小时前
解锁编程新境界:GitHub Copilot 让效率翻倍
人工智能·算法