leetcode40组合总数 Python

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]

思路:看到这道题,马上可以联想到上一题。

这两道题的区别在哪?它们都可以使用数组内任意个数的元素,但上一题能重复,这一题不能重复。还记得上一次我们是如何制造重复的吗?我们在递归函数中设置了一个start参数,他每次手动递归时不加1。这一次不能重复,意思是说我们选了这个元素后就不能再选了,得往后再选一个。

class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        Solution.ans_list = []
        Solution.target = target
        candidates.sort()
        self.DFS(candidates, target, 0, [])
        return Solution.ans_list
 
    def DFS(self, candidates, target, i, valuelist):
        if target == 0 and valuelist not in Solution.ans_list:
            Solution.ans_list.append(valuelist)
        for i in range(i, len(candidates)):
            if candidates[i] > target:
                return
            #与上一道题唯一的区别就在于下面这个递归我们加了1,这样下次递归的循环就从i+1开始了
            self.DFS(candidates, target-candidates[i], i+1, valuelist+[candidates[i]])

leetcode40组合总数 Python_第1张图片

你可能感兴趣的:(LeetCode)