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;
    }
}

原理思路:

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

相关推荐
8Qi82 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
二月夜4 小时前
剖析Java正则表达式回溯问题
java·正则表达式
xuhaoyu_cpp_java5 小时前
项目学习(三)分页查询
java·经验分享·笔记·学习
程序员二叉5 小时前
【Java】集合面试全套精讲|HashMap/ArrayList高频考点完整版
java·面试·哈希算法
cfm_29145 小时前
JVM GC垃圾回收初步了解
java·开发语言·jvm
心之伊始5 小时前
LangChain4j RAG 实战:Java 后端如何把本地文档接入 Embedding 检索链路
java·架构·源码分析·csdn
许彰午6 小时前
17_synchronized关键字深度解析
java·开发语言
小欣加油7 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
Xzh04237 小时前
AI Agent 学习路线(Java 后端方向)
java·人工智能·学习
艾利克斯冰8 小时前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式