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

原理思路:

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

相关推荐
蜗牛互联网27 分钟前
Python Agent工具调用的白名单、参数校验与审批门禁
java·服务器·前端·人工智能·后端·python
Nil20837 分钟前
leetcode 198打家劫舍
算法·leetcode·职场和发展
SL_staff44 分钟前
当规则引擎开始‘懂业务’:JVS-Rules金融风控四大原生能力拆解
java·python·全栈
Shaoshing1 小时前
前缀和与差分
java·数据结构·算法·前缀和·差分
mmmmath_31 小时前
LeetCode.429.N叉树的层序遍历
数据结构·leetcode
dd聊技术1 小时前
Prompt 从代码常量搬进数据库:改一句话,不用再发一次版
java·后端
ly76891 小时前
Spring Data MongoDB 批量写入实践:BulkOperations 批大小与写关注权衡
java·mongodb·spring·批量写入·bulkoperations·写关注·mongotemplate
TAKETODAY1 小时前
Netty 是怎么把 HTTP 请求交给 MVC 的?一个请求的完整链路
java·netty
蚰蜒螟1 小时前
从内核启动到 Java NIO:一次 socket accept 的源码串联之旅
java·python·nio
会编程的吕洞宾2 小时前
Spring AI 2.0 自校正结构化输出实战:让大模型稳定吐出合格 JSON
java·人工智能·后端·spring