版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010870545/article/details/88761843
# coding:utf-8
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(target,temp, start):
if target == 0:
res.append(temp)
return
if target > 0:
for i in range(start, len(candidates)):
c = candidates[i]
dfs(target-c, temp+[c], i)
res=[]
dfs(target, [], 0)
return res
class Solution(object):
def combinationSum2(self, candidates, target):
res = []
candidates.sort()
def backtrack(remain, temp, start):
if remain==0:
res.append(temp)
elif remain > 0:
for i in range(start, len(candidates)):
if candidates[i] > remain:
break
if i > start and candidates[i] == candidates[i-1]:
continue
n = candidates[i]
backtrack(remain-n, temp+[n], i+1)
backtrack(target, [], 0)
return res
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
res = []
# k个数的和是n,就意味着满足条件的子序列,
# 在k = 0 and n = 0,并且是
def dfs(k, n, tmp, start):
if n == 0 and k == 0:
res.append(tmp)
return
for i in range(start, 10):
dfs(k - 1, n - i, tmp+[i], i + 1)
dfs(k, n, [], 1)
return res