LeetCode 39. Combination Sum

本文详细解析了给定一组候选数,在没有重复的情况下找到所有可能的组合,使得这些组合的和等于目标值的问题。介绍了两种解决方案,一种是通过递归实现的直接回溯法,另一种是优化后的递归算法。

Given a set ofcandidate numbers (C(without duplicates) and atarget number (T), find all unique combinations in C wherethe candidate numbers sums to T.

The same repeatednumber 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] andtarget 7
A solution set is: 

[

 [7],

  [2,2, 3]

]

直接回溯:

遍历数组每个元素:选择当前元素---》递归,不选择当前元素---》递归

再加上累计和(sum)与目标(target)比较判断

class Solution {
         List<List<Integer>>ans;
         inttarget;
   public List<List<Integer>> combinationSum(int[] candidates,int target) {
       ans = new ArrayList<List<Integer>>();
       this.target = target;
       Arrays.sort(candidates);
       travelCandidates(candidates,0,0,new ArrayList<Integer>());
       return ans;
    }
 
   public void travelCandidates(int[] candidates,int cur,intsum,List<Integer> list){
             if(cur>=candidates.length) return;
 
             travelCandidates(candidates,cur+1,sum,newArrayList<Integer>(list));
 
             sum += candidates[cur];
             list.add(candidates[cur]);
             if(sum == target){ans.add(list);return;}
             if(sum < target){travelCandidates(candidates,cur,sum,list);}
    }
}

 

提交后只超越了5%的提交者…看了下讨论模块,发现自己递归优化少(能用循环的就少用递归),优化代码:

public class Solution {
   public List<List<Integer>> combinationSum(int[] candidates,int target) {
             Arrays.sort(candidates);
       List<List<Integer>> result = newArrayList<List<Integer>>();
       getResult(result, new ArrayList<Integer>(), candidates, target,0);
        
       return result;
    }
   
   private void getResult(List<List<Integer>> result,List<Integer> cur, int candidates[], int target, int start){
             if(target > 0){
                       for(int i = start; i <candidates.length && target >= candidates[i]; i++){
                                cur.add(candidates[i]);
                                getResult(result,cur, candidates, target - candidates[i], i);
                                cur.remove(cur.size()- 1);
                       }//for
             }//if
             else if(target == 0 ){
                       result.add(newArrayList<Integer>(cur));
             }//else if
    }
}

 

你的代码试图用 **动态规划 + 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() ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值