'''
Author: 365JHWZGo
Description: 40. 组合总和 II
Date: 2021-10-15 09:27:51
FilePath: \test\demo5.py
LastEditTime: 2021-10-15 11:49:35
LastEditors: 365JHWZGo
'''
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
if candidates[0]>target:
return []
if len(set(candidates))==1:
if sum(candidates)==target:
return [candidates]
if sum(candidates)<target:
return []
if sum(candidates)>target:
if target%candidates[0]==0:
return [[candidates[0] for i in range(target//candidates[0])]]
else:
return []
candidates = list(filter(lambda x: x <= target, candidates))
res = []
def backtracking(c, t, res, pres, start):
if t == 0:
pres = pres + []
if pres not in res:
res.extend([pres])
return
for i in range(start, len(c)):
if t < c[i]:
return
pres.append(c[i])
backtracking(c, t - c[i], res, pres, i + 1)
pres.pop()
return res
backtracking(candidates, target, res, [], 0)
return res
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
if candidates[0]>target:
return []
if len(set(candidates))==1:
if sum(candidates)==target:
return [candidates]
if sum(candidates)<target:
return []
if sum(candidates)>target:
if target%candidates[0]==0:
return [[candidates[0] for i in range(target//candidates[0])]]
else:
return []
candidates = list(filter(lambda x: x <= target, candidates))
res = []
uses = [0 for i in range(len(candidates))]
def backtracking(c, t, res, pres, start,uses):
if t == 0:
pres = pres + []
res.extend([pres])
return
for i in range(start, len(c)):
if i>0 and uses[i-1] == 0 and c[i] ==c[i-1]:
continue
if t < c[i]:
return
pres.append(c[i])
uses[i]=1
backtracking(c, t - c[i], res, pres, i + 1,uses)
uses[i]= 0
pres.pop()
return res
backtracking(candidates, target, res, [], 0,uses)
return res