博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode40. Combination Sum II(思路及python解法)
阅读量:2242 次
发布时间:2019-05-09

本文共 1226 字,大约阅读时间需要 4 分钟。

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,A solution set is:[  [1, 7],  [1, 2, 5],  [2, 6],  [1, 1, 6]]

这道题和Combination Sum的思路是一致的,只是这里的数字不能重复使用。(如果candidates里出现重复数字可以使用)

为了提高效率,我们用sort对candidates进行排序,遇到比target大的数字直接break。

然后设定一个起始的索引值,每次遍历便不会出现重复使用情况

class Solution:    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:        self.res=[]        candidates.sort()        self.candidates=candidates        self.dfs(0, [], target)        return self.res        def dfs(self,start,path,target):        if target==0:            self.res.append(path)            return        for i in range(start,len(self.candidates)):            if self.candidates[i]>target:break            if i>start and self.candidates[i]==self.candidates[i-1]:continue            self.dfs(i+1, path+[self.candidates[i]], target-self.candidates[i])

 

转载地址:http://mjrbb.baihongyu.com/

你可能感兴趣的文章
如何实现字符串的反转及替换?
查看>>
Java面试题全集(上)
查看>>
Java面试题全集(中)
查看>>
值传递和引用传递
查看>>
什么情况下用+运算符进行字符串连接比调用StringBuilder对象的append方法连接字符串性能更好?
查看>>
怎么根据Comparable方法中的compareTo方法的返回值的正负 判断升序 还是 降序?
查看>>
理解事务的4种隔离级别
查看>>
常用正则匹配符号
查看>>
建议42: 让工具类不可实例化
查看>>
Java 异步机制与同步机制的区别
查看>>
hibernate的对象三种状态说明
查看>>
什么是N+1查询?
查看>>
Spring 接管 Hibernate 配置 延迟加载
查看>>
找出不在预定数组中的自然数
查看>>
String常见面试题
查看>>
直插,快排,堆排,归并排序的分析
查看>>
二叉树的各种操作(面试必备)
查看>>
oracle
查看>>
泛型与通配符详解
查看>>
BaseServiceImpl中的实现关键点
查看>>