Leetcode39. Combination Sum

本文介绍了解决LeetCode第39题“组合总和”的方法,使用了回溯算法来找出所有可能的数列组合,这些组合中的元素之和等于目标值。代码实现中对输入进行了排序以提高效率,并详细展示了如何递归地添加和移除元素。

Leetcode39. 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.

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

Note:

  • All numbers (including target) will be positive integers.
  • 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]
]

题意分析:这道题,选择用回溯的方法去做。采用的方法也是类似背包问题,先假设放进去,不行再取出来。

void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
	if (!target) {
		res.push_back(combination);
		return;
	}
	for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
		combination.push_back(candidates[i]);
		combinationSum(candidates, target - candidates[i], res, combination, i);
		combination.pop_back();
	}
}

代码:

class Solution {
public:
	std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
		std::sort(candidates.begin(), candidates.end());
		std::vector<std::vector<int> > res;
		std::vector<int> combination;
		combinationSum(candidates, target, res, combination, 0);
		return res;
	}
private:

	void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
		if (!target) {
			res.push_back(combination);
			return;
		}
		for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
			combination.push_back(candidates[i]);
			combinationSum(candidates, target - candidates[i], res, combination, i);
			combination.pop_back();
		}
	}
};


你的代码试图用 **动态规划 + DFS** 的方式解决 [LeetCode 39. Combination Sum](https://leetcode.com/problems/combination-sum/),但目前存在两个关键问题: 1. ❌ **会产生重复组合**(如 `[2,2,3]` 和 `[2,3,2]` 被视为不同) 2. ❌ `dfs(_target-i)` 的调用位置错误,可能导致无限递归或逻辑混乱 --- ## ✅ 核心思想:如何避免重复? > 🔑 **关键技巧:只允许按非降序构造组合** 也就是说,一旦你选择了数字 `x`,之后只能选择 ≥ `x` 的数。这样可以保证每个组合是“有序”的,从而避免 `[2,3,2]`、`[3,2,2]` 这样的重复。 ### ✅ 解决方案:在搜索时记录起始索引 `start` 我们使用标准的 **回溯法(Backtracking)**,并传入一个 `start` 参数,表示从哪个候选数开始选,防止回头选小的数造成重复。 --- ### ✅ 正确且无重复的 Python 实现(推荐) ```python from typing import List, Dict from collections import defaultdict class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: result = [] def backtrack(remain: int, combo: List[int], start: int): if remain == 0: result.append(combo[:]) # 深拷贝 return for i in range(start, len(candidates)): num = candidates[i] if num > remain: continue # 剪枝 combo.append(num) backtrack(remain - num, combo, i) # 允许重复使用当前数字,所以还是 i combo.pop() # 回溯 candidates.sort() # 排序有助于剪枝 backtrack(target, [], 0) return result ``` --- ### 🔍 为什么这样能避免重复? - `start` 参数控制每次只能从当前或后面的数中选择 - 举例:`candidates = [2,3,6,7]`, `target = 7` - 第一次选了 `2` → 后面还能选 `2,3,6,7` - 如果先跳过 `2` 选了 `3` → 后面只能选 `3,6,7`,不会再回头选 `2` - 所以不会出现 `[3,2,2]`,因为选 `3` 后不允许再选前面的 `2` 这就确保了所有组合都是 **非降序排列的唯一形式**,从而去重。 --- ### 🧪 示例输出 输入: ```python s = Solution() print(s.combinationSum([2,3,6,7], 7)) ``` 输出: ```python [[2, 2, 3], [7]] ``` ✅ 没有 `[3,2,2]` 或 `[2,3,2]` 等重复项。 --- ### ❌ 你原代码的问题分析 ```python for i in candidates: if _target >= i: t = num_dict[_target] for j in t: temp = j.copy() temp.append(i) num_dict[_target-i].append(temp) else: break dfs(_target-i) # 错误!这里对每个 i 都调用了 dfs,且未控制顺序 ``` #### 存在问题: 1. **没有控制顺序**:`for i in candidates` 总是从头开始遍历,导致 `[2,3]` 和 `[3,2]` 都被生成。 2. **DFS 调用不当**:`dfs(_target-i)` 放在循环内,会导致多次重复计算和状态混乱。 3. **数据结构设计复杂**:用 `defaultdict(list)` 维护中间结果不如直接回溯清晰。 --- ## ✅ 更优思路总结 | 方法 | 是否推荐 | 说明 | |------|----------|------| | 回溯 + `start` 参数 | ✅ 强烈推荐 | 简洁、易懂、去重自然 | | 动态规划(DP) | ⚠️ 可行但复杂 | 容易产生重复,需额外去重或排序处理 | | BFS / 记忆化搜索 | ❌ 不推荐初学者 | 易出错,维护状态麻烦 | --- ### ✅ 进阶优化:剪枝 由于已排序: ```python if num > remain: break # 后面更大,没必要继续 ``` 替换 `continue` 可进一步提升效率。 修改如下: ```python for i in range(start, len(candidates)): num = candidates[i] if num > remain: break # ✅ 替换 continue 为 break(因为已排序) combo.append(num) backtrack(remain - num, combo, i) combo.pop() ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值