0.原题
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]
]
1.代码
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.result = []
self.one_result = []
self.candidates = candidates
self.fun(target)
return self.result
def fun(self,target):
if target < 0:
return -1
elif target == 0:
r = self.one_result.copy()
r.sort()
if r not in self.result:
self.result.append(r)
return 0
else:
for candidate in self.candidates:
self.one_result.append(candidate)
new_target = target-candidate
self.fun(new_target)
self.one_result.pop()
解题关键点:
本题思路很简单:本题利用递归+遍历,不断地尝试选取candidates中的值,直到满足条件即可。每层递归,另target = target - candidate,如果target == 0 ,即表示找到了一组解。
难点在于,如何判重?比如[2,3,3]、[3,2,3]、[3,3,2]都是一组解。
将符合条件的解(列表)进行排序操作,那么[2,3,3]、[3,2,3]、[3,3,2]排序之后都是[2,3,3],这样就解决了判重问题。
代码中需要注意的地方:
在这段代码中,我们执行了r = self.one_result.copy()操作,因为list是mutable object,不拷贝直接使用,则传递是self.one_result的指针,那么result中保存的只有self.one_result的最终结果。具体原因详见:
https://blog.csdn.net/qq_17753903/article/details/82886625
另外,对one_result的排序也必须在副本上进行,即r.sort()。因为,递归返回后,要执行one_result.pop()操作,如果对one_result先进行了排序,那么弹出的就不一定是最后一个元素了,从而导致程序错误。