leetcode专题训练 40. Combination Sum II

本文探讨了一种组合求和问题的解决方法,并进行了代码优化。首先介绍了使用Counter函数计算数字出现次数的方法,随后提出了一种更高效的解决方案,通过直接遍历候选数字列表并递归求解,显著减少了运行时间。
  1. 最开始的时候沿用了上一题的思路,然而这道题又有所不同
  • 由于这一题不是单个数字任意次数选取,而是按照题目中次数选取,所以用了Counter函数来计算每个数字次数,在循环时,退出条件多了一条当前数字出现次数不超过所给列表中次数,其他与上一题基本相似。
  • 由于上一题中相同元素不会出现在列表中,所以在递归给下一层时,切片只用切掉当前元素即可,而本题列表中会出现相同元素,所以在递归给下一层时,切片要切掉所有与当前元素相同元素。

本题用python3提交时总显示错误,估计是后台验题代码的问题,所以将代码改成了python2的代码。

from collections import Counter


class Solution(object):
    def solve(self, candidates, lst, target):
        result = []
        l = len(candidates)
        count = Counter(candidates)
        for i in range(l):
            if candidates[i] > target:
                break
            if i > 0 and candidates[i] == candidates[i-1]:
                continue;
            tmp = 0
            tmpl = []
            for j in range(0, count[candidates[i]]):
                tmp += candidates[i]
                tmpl.append(candidates[i])
                if tmp > target:
                    break
                if tmp == target:
                    result.append(lst+tmpl)
                    break
                result += self.solve(candidates[i+count[candidates[i]]:], lst+tmpl, target-tmp)
        return result
    
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        solution = Solution()
        return solution.solve(candidates, [], target)
        
  1. 在代码通过后,发现自己的代码所用时间相比于其他代码长,所以又去更改了自己的代码。这个代码就不需要计算每个元素出现的个数了,直接扫描一遍candidates就可以了,时间大大减少。
class Solution(object):
    def solve(self, candidates, lst, target):
        l = len(candidates)
        result = []
        for i in range(l):
            if candidates[i] > target:
                break
            if i > 0 and candidates[i] == candidates[i-1]:
                continue
            if candidates[i] == target:
                result.append(lst+[candidates[i]])
                break
            result += self.solve(candidates[i+1:], lst+[candidates[i]], target-candidates[i])
        return result
    
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        solution = Solution()
        return solution.solve(candidates, [], target)
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值