博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode之Combination SumII
阅读量:2342 次
发布时间:2019-05-10

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

与Combination Sum不同之处在candidates数组中的元素最多只能用一次,且结果集必须不含有重复元素,方法为:

当前元素跟前一个元素是相同的时候,如果前一个元素被取了,那当前元素可以被取,也可以不取,反过来如果前一个元素没有取,那我们这个以及之后的所以相同元素都不能被取。

class Solution(object):    def combinationSum2(self, candidates, target):        """        :type candidates: List[int]        :type target: int        :rtype: List[List[int]]        """        result = []        lenofcan = len(candidates)        if lenofcan == 0:            return result        currentresult = []        index = 0        candidates.sort()        self.backtracking(candidates, index, target, result, currentresult, lenofcan)        return result        def backtracking(self, candidates, index, lefttarget, result, currentresult, lenofcan):        if lefttarget == 0:            result.append(currentresult)            return                    if index > lenofcan - 1:            return                    factor = lefttarget / candidates[index]        if factor == 0:            return                copylefttarget = lefttarget        for i in range(2):            skip = 1            copycurrentresult = copy.deepcopy(currentresult)            copylefttarget = lefttarget - i * candidates[index]            if i == 1:                copycurrentresult.append(candidates[index])            if i == 0:                while index + skip < lenofcan and candidates[index] == candidates[index + skip]:                    skip += 1            self.backtracking(candidates, index + skip, copylefttarget, result, copycurrentresult, lenofcan)

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

你可能感兴趣的文章
spring boot日志配置
查看>>
list排序
查看>>
搭建zookeeper集群
查看>>
1005. 数独
查看>>
1006. 求和游戏
查看>>
IDEA eclipse 控制台日志输出到文件
查看>>
1022. Fib数列
查看>>
一些开源项目
查看>>
将博客搬至CSDN
查看>>
MySQL 中事务的实现
查看>>
CheckStyle
查看>>
IDE配置jvm参数
查看>>
内存溢出
查看>>
Spring Cloud 声明式服务调用 Feign
查看>>
JVM实用参数(一)JVM类型以及编译器模式
查看>>
spring cloud config 属性加解密
查看>>
rabbitmq安装
查看>>
RabbitMQ 使用
查看>>
动态代理
查看>>
oracle中merge into用法解析
查看>>