• LeetCode刷题系列 -- 40. 组合总和 II


    给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的每个数字在每个组合中只能使用 一次 。

    注意:解集不能包含重复的组合。 

    示例 1:

    输入: candidates = [10,1,2,7,6,1,5], target = 8,
    输出:
    [
    [1,1,6],
    [1,2,5],
    [1,7],
    [2,6]
    ]
    示例 2:

    输入: candidates = [2,5,2,1,2], target = 5,
    输出:
    [
    [1,2,2],
    [5]
    ]
     

    提示:

    1 <= candidates.length <= 100
    1 <= candidates[i] <= 50
    1 <= target <= 30

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/combination-sum-ii
     

    思路:回溯算法秒杀所有排列/组合/子集问题 :: labuladong的算法小抄

    回溯算法。
    1. 数组排序
    2. 定义数组  used ,长度为  nums.length , used[i] 代表 nums[i] 是否被放入子集中
    3. 回溯算法遍历数组。注意剪枝问题:

    java:

    1. class Solution {
    2. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    3. List<List<Integer>> result = new LinkedList<>();
    4. boolean[] used = new boolean[candidates.length];
    5. Arrays.sort(candidates);
    6. backtrack(candidates, target, 0, 0,used, new LinkedList<>(), result);
    7. return result;
    8. }
    9. public void backtrack(int[] candidates, int target, int start, int subSetSum, boolean[] used,List<Integer> subSet, List<List<Integer>> result) {
    10. if(subSetSum==target) {
    11. result.add(new LinkedList<>(subSet));
    12. return;
    13. }
    14. // 组合的和大于 target 时,就不需要再递归了
    15. if(subSetSum>target) {
    16. return;
    17. }
    18. for(int i=start;i<candidates.length;i++) {
    19. // 剪枝。 与前面的子集 II 的剪枝逻辑是一样的,相同的元素不需要再递归一次,不然就重复了
    20. if(i>0&&candidates[i-1] == candidates[i] && !used[i-1]) {
    21. continue;
    22. }
    23. used[i] = true;
    24. subSetSum += candidates[i];
    25. subSet.add(candidates[i]);
    26. backtrack(candidates,target,i+1,subSetSum,used,subSet,result);
    27. used[i] = false;
    28. subSetSum -= candidates[i];
    29. subSet.remove(subSet.size()-1);
    30. }
    31. }
    32. }

  • 相关阅读:
    AES简写
    链表(一)——无头单向非循环链表实现
    Vue学习笔记
    redis(1)-hiredis-Windows下的编译
    (三) CPU 性能测试 (CPU负载高对应的不同情况)
    [题] 差分 #差分
    QFtp编译
    【机器学习】线性分类【下】经典线性分类算法
    web程序课程记录
    基于生物地理学优化的BP神经网络(分类应用) - 附代码
  • 原文地址:https://blog.csdn.net/qq_33775774/article/details/126446038