LeetCode:40. 组合总和 II(回溯 + 剪枝 Java)

目录

[40. 组合总和 II](#40. 组合总和 II)

题目描述:

实现代码与解析:

[回溯 + 剪枝](#回溯 + 剪枝)

原理思路:


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

实现代码与解析:

回溯 + 剪枝

java 复制代码
class Solution {


    private List<Integer> path = new ArrayList();
    private List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {

        Arrays.sort(candidates);

        dfs(candidates, 0, target, 0);

        return res;
    }


    public void dfs(int[] candidates, int cur, int target, int idx) {

        if (cur == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (idx >= candidates.length) return;
        if (cur + candidates[idx] > target) return; // 如果大于,剪枝

        for (int i = idx; i < candidates.length; i++) {
            if (i > idx && candidates[i] == candidates[i - 1]) { // 同一位置不能重复选相同的数
                continue;
            }
            path.add(candidates[i]);
            dfs(candidates, cur + candidates[i], target, i + 1);
            path.remove(path.size() - 1); // 回溯
        }
        return;
    }
}

原理思路:

比较简单啊,看代码吧。回溯题。

相关推荐
一匹电信狗6 分钟前
【LeetCode_876_2.02】快慢指针在链表中的简单应用
c语言·数据结构·c++·算法·leetcode·链表·stl
我是华为OD~HR~栗栗呀18 分钟前
华为OD-Java面经-21届考研
java·c++·后端·python·华为od·华为·面试
码农多耕地呗24 分钟前
力扣543.二叉树的直径(java)(迭代法 and 左右根后序遍历迭代法)
算法·leetcode·职场和发展
考虑考虑27 分钟前
流收集器
java·后端·java ee
今天背单词了吗98034 分钟前
Spring Boot+RabbitMQ 实战:4 种交换机模式(Work/Fanout/Direct/Topic)保姆级实现
java·spring·中间件·rabbitmq·1024程序员节
九皇叔叔1 小时前
Java循环结构全解析:从基础用法到性能优化
java·开发语言·性能优化
仰泳的熊猫1 小时前
LeetCode:200. 岛屿数量
数据结构·c++·算法·leetcode
流星5211221 小时前
GC 如何判断对象该回收?从可达性分析到回收时机的关键逻辑
java·jvm·笔记·学习·算法
csdn_aspnet1 小时前
Java 圆台体积和表面积计算程序(Program for Volume and Surface area of Frustum of Cone)
java
杯莫停丶1 小时前
设计模式之:外观模式
java·设计模式·外观模式