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);
    }
}
相关推荐
凤年徐3 分钟前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
kualcal7 分钟前
代码随想录17|二叉树的层序遍历|翻转二叉树|对称二叉树
数据结构·算法
满分观察网友z1 小时前
从混乱到有序:我用“逐层扫描”法优雅搞定公司组织架构图(515. 在每个树行中找最大值)
后端·算法
满分观察网友z1 小时前
一行代码的惊人魔力:从小白到大神,我用递归思想解决了TB级数据难题(3304. 找出第 K 个字符 I)
后端·算法
字节卷动1 小时前
【牛客刷题】活动安排
java·算法·牛客
yi.Ist2 小时前
数据结构 —— 键值对 map
数据结构·算法
s153352 小时前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
Coding小公仔2 小时前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七2 小时前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
DoraBigHead3 小时前
小哆啦解题记——异位词界的社交网络
算法