Leetcode 组合总和专题
组合总和专题在leetcode上总共有四道,本专题集中解决。
1
第一题:无重复数组, 可重复使用数字, 集合不能重复
最基础的题目,主要思想是利用dfs和回溯。每种方法都考虑并且去尝试遍历所有可能。
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
def dfs(ans, now, index):
if now == target:
res.append(ans[:])
return
for i in range(index,len(candidates)):
now += candidates[i]
if now >target:
return
ans.append(candidates[i])
dfs(ans, now, i)
now