第一版本代码:
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
self.ans = []
vis = [0 for i in range(len(candidates))]
self.dfs(candidates,[],vis,0,target)
return self.ans
def dfs(self,nums,tem,vis,start,target):
if target==0 and tem not in self.ans:
self.ans.append(tem.copy())
return
if target<0:
return
for i in range(start,len(nums)):
if nums[i]>target:
break
if vis[i]==0:
tem.append(nums[i])
vis[i] = 1
self.dfs(nums,tem,vis,i,target-nums[i])
tem.pop()
vis[i]=0
用vis来判断是否使用
并且没有一个很好的去重方法
第二版本:
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
self.ans = []
self.dfs(candidates,[],0,target)
return self.ans
def dfs(self,nums,tem,start,target):
if target==0 :
self.ans.append(tem.copy())
return
if target<0:
return
for i in range(start,len(nums)):
if nums[i]>target:
break
if i>start and nums[i]==nums[i-1]:
continue
tem.append(nums[i])
self.dfs(nums,tem,i+1,target-nums[i])
tem.pop()
用start = i+1 来控制只使用一次,因为[i+1:]都是没有使用过的
去重:这个很有技巧性,学会来
if i>0 and nums[i]==nums[i-1] continue
if i>start and nums[i]==nums[i-1] continue
样例 [1,1,6,6]
来源:CSDN
作者:不知道你在说什么
链接:https://blog.csdn.net/a870735654/article/details/103237424