给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
下面先附上代码:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
n=len(candidates)
def dfs(candidates,begin,size,path,res,target):
if target==0:
res.append(path)
return
for index in range(begin,size):
if candidates[index]>target:
break
dfs(candidates,index+1,size,path+[candidates[index]],res,target-candidates[index])
res=[]
path=[]
candidates.sort()
dfs(candidates,0,n,path,res,target)
res = list(set([tuple(t) for t in res]))
return res
这道题的考点还是使用回溯法去解决问题,而且重点在于题目中给定的元素不可重复使用,所以这就涉及到了如何在二维数组中去重,二维数组去重和一维数组不同,下面贴上其他博主所使用的去重方法:(原文:https://blog.csdn.net/yangyang_yangqi/article/details/84930167?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param)
一维的list去重可以用set(list),但是二维的list转set就会报错 unhashable type: ‘list’
原因是set传进来的是不可哈希的变量
Python中那么哪些是可哈希元素?哪些是不可哈希元素?
可哈希的元素有:int、float、str、tuple
不可哈希的元素有:list、set、dict
为什么 list 是不可哈希的,而 tuple 是可哈希的
(1)因为 list 是可变的在它的生命期内,你可以在任意时间改变其内的元素值。
(2)所谓元素可不可哈希,意味着是否使用 hash 进行索引
(3)list 不使用 hash 进行元素的索引,自然它对存储的元素有可哈希的要求;而 set 使用 hash 值进行索引
正确做法:将list转成tuple,这样就可以用set去重。
dic = list(set([tuple(t) for t in dic]))
dic = [list(v) for v in dic]