Leetcode_med 40. 组合总和 II

描述

给定一个数组 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]
]

Python

与39题极为类似,仍然是回溯法,只增加了两条if判断,将最后的i变成i+1即可实现

class Solution:
    def combinationSum2(self, candidates, target):
        res = []
        candidates.sort()
        self.backtracking(candidates,target,0,[],res)
        return res
    
    def backtracking(self,candidates,target,index,member,res):
        if target < 0:return 
        if target == 0:
            res.append(member)
        if index<len(candidates) and target < candidates[index]:
            return
        for i in range(index,len(candidates)):
            if i>index and candidates[i] == candidates[i-1]:continue
            self.backtracking(candidates,target-candidates[i],i+1,member+[candidates[i]],res)
                
            
全部评论

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
秋招吐槽大会
点赞 评论 收藏
分享
26应届求职ing:你这是报了豆音四哥的班?双非本硕拿这两个项目写简历里投100多家嵌软也没什么面试,感觉项目简单了,很多人用
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务