组合总和

# 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 
#
# candidates 中的数字可以无限制重复被选取。
#
# 说明:
#
#
# 所有数字(包括 target)都是正整数。
# 解集不能包含重复的组合。
#
#
# 示例 1:
#
# 输入:candidates = [2,3,6,7], target = 7,
# 所求解集为:
# [
# [7],
# [2,2,3]
# ]

方法:回溯

def combinationSum(nums, target):
    res = []
    if len(nums) == 0:
        return res    # 返回空list
    nums.sort()     # 来一次排序,便于后续处理
    dfs(nums, [], target, 0, res)   # 深度优先遍历,直接到底,递归回溯
    return res
def dfs(nums, sublist, target, last, res):    # last表示sublist的最后一个元素
    if target == 0:
        res.append(sublist)
    if target < nums[0]:   # 剪枝,小于第一个元素值直接返回
        return
    for each in nums:   # 数字可以重复使用,每次都再次循环遍历
        if each > target:  # 剪枝,当前数字如果大于目标值,后面无需遍历
            return
        if each < last:   # 剪枝操作:若当前数值小于当前sublist的最后一个元素,则继续遍历,防止出现重复解决方案,如[2,2,3],[3,2,2]
            continue
        dfs(nums, sublist+[each], target-each, each, res)
时刻记着自己要成为什么样的人!
原文地址:https://www.cnblogs.com/demo-deng/p/14956602.html