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 分钟前
74. 搜索二维矩阵
c++·leetcode·矩阵·二分查找
programhelp_5 分钟前
Snowflake OA 2026 面经|3道高频真题拆解 + 速通攻略
经验分享·算法·面试·职场和发展
圣保罗的大教堂6 分钟前
leetcode 3740. 三个相等元素之间的最小距离 I 简单
leetcode
Duang6 分钟前
AI 真能自己写出整个 Windows 系统吗?我做了一场无监督实验
算法·设计模式·架构
少许极端9 分钟前
算法奇妙屋(四十五)-CCPC备战之旅-1
java·开发语言·算法
无小道10 分钟前
算法——找规律
算法·规律
圣保罗的大教堂41 分钟前
leetcode 2069. 模拟行走机器人 II 中等
leetcode
地平线开发者1 小时前
目标检测的 Anchor-Free 和 NMS 到底是什么?
算法·自动驾驶
北顾笙9801 小时前
day24-数据结构力扣
数据结构·算法·leetcode
智者知已应修善业1 小时前
【51单片机独立按键控制往复流水灯启停】2023-6-13
c++·经验分享·笔记·算法·51单片机