Combination Sum算法详解

本文详细介绍了Combination Sum系列算法,包括Combination Sum I、II和III。针对每种情况,阐述了题意、约束条件,并给出了递归求解的思路。例如,给定正数集合和目标数,找出所有递增排列且不重复的子集合,使得子集合的元素和为目标数。文章通过示例解释了解题过程。

Combination Sum I:
算法题目: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 number of times.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]

题意:给定一个正数集合和一个目标数,求出所有的子集合,使子集的和为target,要求子集合递增排列,且不包含重复的子集合,子集合中的数字可以重复

思路:先排序,递归求所有数字的集合,并判断数是否等于target

    void CombinationSumCore(const vector<int>& candidates,vector<vector<int>>& res,vector<int>& com,int target,int pos)
    {
        if(target==0)
        {
            res.push_back(com);
            return;
        }
        for(int i=pos;i<candidates.size();i++)
        {
            
**题目重述:** 给定一个整数数组 `nums` 和一个目标值 `target`,请你找出所有唯一组合,使得组合中的元素之和等于 `target`。每个组合中的元素来自数组中的不同位置,且顺序无关(即 `[1,2]` 和 `[2,1]` 是相同的组合)。 说明: - 数组中的元素可以重复使用,但最终结果中不能包含重复的组合。 - 数组中元素均为正整数。 - 结果按字典序排序。 例如: 输入: ```python nums = [1, 2, 3] target = 4 ``` 输出: ```python [ [1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2] ] ``` --- **详解:** 这是一个典型的 **回溯算法** 题目,要求我们找到所有满足条件的组合,其中组合中的元素之和等于目标值,并且不允许重复的组合出现。 **解题思路:** 1. 使用递归的方式进行深度优先搜索(DFS)尝试所有可能的组合。 2. 为避免重复组合,规定每次选择元素时只能从当前索引开始往后选(包括当前元素)。 3. 每当我们找到一组组合使得总和等于 `target`,就将该组合加入结果集中。 4. 若当前总和已经超过 `target`,则剪枝停止这一条路径的搜索。 **Python 示例代码如下:** ```python def combination_sum(nums, target): res = [] def dfs(start, path, total): if total == target: res.append(path[:]) return if total > target: return for i in range(start, len(nums)): path.append(nums[i]) dfs(i, path, total + nums[i]) # 允许重复选取 path.pop() combination_sum.dfs(0, [], 0) # 排序以保证结果一致 res.sort() return res ``` --- **知识点:** 1. **回溯算法** - 回溯算法是一种通过递归尝试所有可能解的方法,适用于组合、排列、子集等问题。 2. **剪枝优化** - 在递归过程中提前判断不可能达到目标的情况,减少无效计算。 3. **去重处理** - 通过控制起始索引避免生成重复的组合,是解决组合问题中重复结果的常用技巧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值