40. leetcode题目讲解(Python): 组合总和 2 II(Combination Sum II)

题目如下:

40. leetcode题目讲解(Python): 组合总和 2 II(Combination Sum II)_第1张图片
题目

解题思路:

这道题跟上一题(39题)非常类似,不同之处是这道题不允许重复使用candidates中的元素。我们可以直接在上一道题目的代码上修改,递归的时候将 idx 加 1(需判断是否超出candidates的范围),另外由于题目输入的candidates可能包含相同的元素,所以我们需要对得到的答案进行去重处理。

参考代码:


class Solution:
    def Slover(self, candidates, target, res, path, idx):
        for i in range(idx, len(candidates)):
            new_target = target - candidates[i]
            if new_target < 0:
                return
            else:
                if new_target == 0:
                    res.append(path + [candidates[i]])
                else:
                    idx = idx + 1
                    if idx < len(candidates):
                        self.Slover(candidates, new_target, res, path + [candidates[i]], idx)
                    else:
                        return
                    
            
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        path = []
        idx = 0
        candidates = sorted(candidates)
        self.Slover(candidates, target, res, path, idx)
        ud_res = []
        for r in res:
            if r not in ud_res:
                ud_res.append(r)
        return ud_res


源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

你可能感兴趣的:(40. leetcode题目讲解(Python): 组合总和 2 II(Combination Sum II))