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

原理思路:

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

相关推荐
一定要AK23 分钟前
Spring 入门核心笔记
java·笔记·spring
A__tao24 分钟前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
KevinCyao37 分钟前
java视频短信接口怎么调用?SpringBoot集成视频短信及回调处理Demo
java·spring boot·音视频
迷藏49443 分钟前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
skywalker_111 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg2 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒2 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
wuxinyan1232 小时前
Java面试题47:一文深入了解Nginx
java·nginx·面试题
新知图书2 小时前
搭建Spring Boot开发环境
java·spring boot·后端