Leetcode 39. Combination Sum

本文详细解析了如何使用深度优先搜索(DFS)算法解决组合总和问题,即给定一组候选数和目标数,找出所有可能的组合使候选数之和等于目标数。文章提供了Python代码实现,并解释了关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]
]

一般跟求combiantion相关的题目基本上都会用到DFS。这里需要注意的是,用L22可以代替L23-L25。因为L22并没有改变 line, 所以line+[x]在内存中其实被另外的单独存储,所以不用line.pop()。

 1 class Solution(object):
 2     def combinationSum(self, candidates, target):
 3         """
 4         :type candidates: List[int]
 5         :type target: int
 6         :rtype: List[List[int]]
 7         """
 8         candidates.sort()
 9         
10         res = []
11         line = []
12         self.helper(candidates, target, res, line)
13         return res
14         
15     def helper(self, candidates, target, res, line):
16         if target == 0:
17             res.append([x for x in line])
18             return 
19     
20         for i, x in enumerate(candidates):
21             if x <= target:
22             #    self.helper(candidates[i:], target-x, res, line+[x])
23                 line.append(x)
24                 self.helper(candidates[i:], target-x, res, line)
25                 line.pop()
26     

 

转载于:https://www.cnblogs.com/lettuan/p/6250984.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值