【LeetCode】解题39:Combination Sum

Leetcode 39. Combination Sum --数组元素组合,和为目标值,一个元素可用无数次,输出每种组合,每种组合唯一 Given asetof candidate numbers (candidates)(without duplicates)and a target number (target), find all unique combinations incandidateswhere the candidate numbers sums totarget. Thesamerepeat... 阅读详情

Problem 39: Combination Sum [Medium]

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

来源:LeetCode

解题思路

基本思路为回溯算法,采用深度优先,并使用剪枝减少无用搜索。

  • 首先将候选数组按升序排序。
  • 每一轮循环从候选数组中选择一个数x加入组合,比较target'与x的大小,此处target'代表每一轮中新的目标值,根据比较结果分为三种情况:
    a. 如果target' - x = 0,说明组合中sum = target,将该种组合加入最终结果result列表里,并剪枝。
    b. 如果target' - x < 0,说明组合中sum > target,不能再加入任何数,也不能将x替换为更大的候选数,因此这里直接剪枝。
    c. 如果target' - x > 0,说明组合中sum < target,还可以继续深入搜索,更新target' = target' - x,进行递归搜索。
  • 注意:为了防止重复组合,每次选择的数x不能比已经存在于组合中的数小,因此递归时需要增加搜索范围参数,不能再次访问之前已经搜索完全的下标。

如下图所示,候选数组为[2,3,6,7],target为7,按深度优先策略,每一轮减去一个数观察剩余的目标值,小于或等于0时都要进行剪枝。其中带颜色的节点为叶节点,表示不再递归搜索,橙色的叶节点代表搜索路径上选择的数属于正确的组合。
回溯算法
要点:回溯算法剪枝

Solution (Java)

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        int N = candidates.length;
        if(N == 0) return result;
        List<Integer> comb = new ArrayList<Integer>();
        backtracking(candidates, 0, N, target, comb, result);
        return result;
    }
    private void backtracking(int [] candidates, int index, int N, int target, List<Integer> comb, List<List<Integer>> result){
        for(int i = index; i < N; i++){
            int next_target = target - candidates[i];
            if(next_target == 0){
                comb.add(candidates[i]);
                result.add(comb);
                return;
            }
            else if(next_target < 0){
                return;
            }
            else{
                List<Integer> next_comb = new ArrayList<Integer>(comb);
                next_comb.add(candidates[i]);
                backtracking(candidates, i, N, next_target, next_comb, result);
            }
        }
    }
}

修改过程

  • 没有在递归前创造新的列表空间,供后续选择不同的数,导致搜索过程中所有的数都加入了同一个组合。
Qt C++ 信号发生器控制软件 waveformComboBox->addItems({"正弦波", "方波", "三角波", "锯齿波", "脉冲波"});frequencyLabel = new QLabel("频率 (Hz):");amplitudeLabel = new QLabel("幅值 (V):");offsetLabel = new QLabel("直流偏移 (V):");} else if (currentWaveform == "三角波") {} else if (currentWaveform == "方波") { 阅读详情

相关推荐

第8章 - 异构系统的协同控制及最优控制 --> 最优控制

异构系统的协同控制及最优控制 --> 协同控制

赵继超的笔记 2229

LeetCode 39 && 40 Combination Sum I && II 关键在于剪枝剪枝讨论在末尾

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited numb

gx262091291的专栏 523

SQLServer2014企业版64位官方简体中文版(附详细安装教程)

SQL Server 2014企业版很多人都会简称为SQL2014企业版,SQL2014企业版是由微软推出的分布式数据库管理系统,一些专业的服务器使用的数据库存储方式就是sql方式,这个版本在安全性、管理性、T-SQL增强、SSIS集成服务,SSAS分析服务以及SSRS报表服务等方面均有所提升,新版本还启用了全新的混合云解决方案,让你管理数据库更加轻松,小编还为大家整理了SQL Server 20

Leetcode 39 Combination Sum(组合总和)

@Leetcode 本题与Leetcode216 组合总和III以及LeetCode77 Combinations的区别是,集合里面的元素可以重复使用,故递归没有层数限制,只要选取元素总和为target,即可返回。而另外两个知道得递归k层,因为要取k个元素的集合。 回溯三步曲 递归函数参数 void generateSum(vector<int>& candidates, int target, int startIndex, int &sum, vector<int&

weixin_42438346的博客 272

LeetCodeCombination Sum算法过程详解

讨论区的解法基本都是回溯和递归,说到回溯递归基本就一句话“自己调用自己”,而实际运行过程总是让人很晕。现为了方便详细分析整个算法过程,选取candidates数组只包含两个数{2,4};target=6; class Solution { public List<List<Integer>> combinationSum(int[] candidates, int...

kaylee_study的博客 286

LeetCode 39. 组合总和 Combination Sum(C语言)

题目描述: 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。 示例 1: 输入: candidates = [2,3,6,7], target = 7, 所求解...

hang404的博客 1110

LeetCode刷题:39. Combination Sum

LeetCode刷题:39. Combination Sum 原题链接:https://leetcode.com/problems/combination-sum/description/ Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique comb...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 282

LeetCode 39. Combination Sum 题解

本题是回溯算法的经典问题,主要考察对回溯思想的理解和应用。通过维护一个路径数组和起始索引,我们可以生成所有可能的组合,并确保不重复。回溯算法的核心思想是:通过选择、递归、回溯的过程,遍历所有可能的解空间,找到符合条件的解。可以重复选择同一元素,因此递归调用时起始索引仍为当前索引。为了避免重复组合,我们从起始索引开始遍历,而不是从数组的开头。当当前和大于目标值时,停止继续选择,进行剪枝,提高效率。这种方法不仅适用于组合总和问题,还可以应用于许多其他组合问题,例如子集问题、排列问题等。

cannonjinx的博客 2169

【小白爬Leetcode39】数组总和 Combination Sum

【小白爬Leetcode39】数组总和 Combination Sum题目方法一 暴力搜索(反例,不完全递归)方法二 回溯方法三 剪枝 题目 Leetcode39 medium\color{#ffaa00}{medium}medium 点击进入原题链接:数组总和 Combination Sum Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find al

weixin_41604040的博客 215

回溯详解及其应用:Leetcode 39 combination sum

原理 初入门 基本定义和概念 举栗子 编程思路 实践 生成符合规范的括号 combination sum n queen原理初入门有时会遇到这样一类题目,它的问题可以分解,但是又不能得出明确的动态规划或是递归解法,此时可以考虑用回溯法解决此类问题。回溯法的优点 在于其程序结构明确,可读性强,易于理解,而且通过对问题的分析可以大大提高运行效率。但是,对于可以得出明显的递推公式迭代求解的问题,还是不要用

I AM BACK 4623

[LeetCode] 039. Combination Sum (Medium) (C++)

[LeetCode] 039. Combination Sum (Medium) (C++)

水果君の日常 2345

LeetCode解题40:Combination Sum II

LeetCode解题 40:Combination Sum II Problem 40: Combination Sum II [Medium]解题思路Solution (Java)修改过程 Problem 40: Combination Sum II [Medium] Given a collection of candidate numbers (candidates) and a targe...

Fayedily的博客 246

[leetcode javascript解题]Combination Sum

leetcode39Combination Sum描述如下: Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The sam

zzxboy1的博客 783

Leetcode算法学习日志-39 Combination Sum

Leetcode 39 Combination Sum 题目原文 Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Th

Zarlove的博客 343

LeetCode解题126:Word Ladder II(BFS算法

LeetCode解题 126:Word Ladder II(BFS算法)Problem 126: Word Ladder II [Hard]解题思路Solution (Java)修改过程 Problem 126: Word Ladder II [Hard] Given two words (beginWord and endWord), and a dictionary’s word list, ...

Fayedily的博客 771

LeetCode解题188:Best Time to Buy and Sell Stock IV(动态规划)

LeetCode解题 188:Best Time to Buy and Sell Stock IV (动态规划)Problem 188: Best Time to Buy and Sell Stock IV [Hard]解题思路Solution (Java)修改过程 Problem 188: Best Time to Buy and Sell Stock IV [Hard] Say you hav...

Fayedily的博客 594

LeetCode解题123:Best Time to Buy and Sell Stock III(动态规划)

LeetCode解题 123:Best Time to Buy and Sell Stock III (动态规划)Problem 123: Best Time to Buy and Sell Stock III [Hard]解题思路I. O(2n)时间+O(3n)空间II. O(2n)时间+O(n)空间III. O(n)时间+O(4)空间Solution (Java) Problem 123: B...

Fayedily的博客 487

LeetCode解题119:Pascal's Triangle II

LeetCode解题 118:Pascal's Triangle II Problem 118: Pascal's Triangle II [Easy]解题思路Solution (Java) Problem 118: Pascal’s Triangle II [Easy] Given a non-negative index k where k ≤ 33, return the kth index...

Fayedily的博客 444

LeetCode解题78:Subsets

LeetCode解题 78:Subsets Problem 78: Subsets [Medium]解题思路Solution (Java)修改过程 Problem 78: Subsets [Medium] Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The so...

Fayedily的博客 443

LeetCode解题44:Wildcard Matching(动态规划解法)

LeetCode解题 44:Wildcard Matching(动态规划解法)Problem 44: Wildcard Matching [Hard]解题思路Solution (Java) Problem 44: Wildcard Matching [Hard] Given an input string (s) and a pattern (p), implement wildcard patt...

Fayedily的博客 429

LeetCode解题10:Regular Expression Matching(动态规划解法)

LeetCode解题 10:Regular Expression Matching(动态规划解法)Problem 10: Regular Expression Matching [Hard]解题思路Solution (Java) Problem 10: Regular Expression Matching [Hard] Given an input string (s) and a patter...

Fayedily的博客 411
上一篇: 【LeetCode】解题35:Search Insert Position
下一篇: 【LeetCode】解题40:Combination Sum II
Fayedy
博客等级 码龄11年 2粉丝 57原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值