练习2

1.(39题->组合总和 ->回溯+剪枝)

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是唯一的。 对于给定的输入,保证和为 target 的唯一组合数少于 150 个。

示例 1:

输入: candidates = [2,3,6,7], target = 7
输出: [[7],[2,2,3]]


示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]


示例 3:

输入: candidates = [2], target = 1
输出: []


示例 4:

输入: candidates = [1], target = 1
输出: [[1]]
示例 5:

输入: candidates = [1], target = 2
输出: [[1,1]]

分析:使用candidates = [2,3,7] ,target = 7 画树形图

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates = sorted(candidates)
        n = len(candidates)
        ans = []
        path = [] #储存中间结果
        sum1 = 0 #计算中间结果累加和,用于剪枝

        def backtrank(candidates,sum1,target):
            if sum1 == target:
                return ans.append(path[:])
            for i in range(n):
                if path and candidates[i] < path[-1]:
                    continue
                if sum1 + candidates[i] > target:#使用sum1剪枝
                    return#当sum1+x>target时,使用return停止生成叶子节点
                else:
                    sum1 += candidates[i]
                path.append(candidates[i])
                backtrank(candidates,sum1,target)
                sum1 -= candidates[i]
                path.pop()
        backtrank(candidates,sum1,target)
        return ans

nums = [2,3,7]
target = 7
solution = Solution()
result = solution.combinationSum(nums,target)
print(result)
View Code

>>待续

原文地址:https://www.cnblogs.com/wuxunyan/p/15038912.html