leetcode专题训练 40. Combination Sum II

  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)
        
发布了201 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/96618314