40. 组合总和 II-递归dfs+剪枝-中等难度

问题描述

给定一个数组 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]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii

解答

'''
递归+深度优先搜索+剪枝,不然会超时。
先排序(便于剪枝和去重),画出递归树,适当剪枝,再深度优先遍历。
'''

class Solution(object):
    def combinationSum2(self, candidates, target):
        result = []
        target1 = target
        candi = []
        for i in range(0,len(candidates)):
            if candidates[i] <= target:
                candi.append(candidates[i])
        candi.sort()
        def dfs(self, candidates, arr, result, target1):
            if not candidates or target1 == 0:
                if arr not in result and target1 == 0:
                    result.append([])
                    result[-1].extend(arr)
                    target1 = target
                return 0
            
            if target1 >= candidates[0]:
                arr.append(candidates[0])
                target1 -= candidates[0]
                dfs(self, candidates[1:], arr, result, target1)
                arr.pop()
                target1 += candidates[0]
                dfs(self, candidates[1:], arr, result, target1)
            else:
                return 0
        arr = []
        dfs(self, candi, arr, result, target1)
        return result
原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13231185.html