求列表中k个数字和为target的所有组合-python

方法一

深度优先遍历

def k_sum(nums, k, target):
    if not nums:
        return
    subsets = []
    dfs(nums, 0, k, target, [], subsets)
    return subsets
# 1.递归的定义
def dfs(nums, index, k, target, subset, subsets):
    # 2.递归的出口
    if k == 0 and target == 0:
        subsets.append(subset[:])
        return
    if k == 0 or target <= 0:
        return
    # 递归的拆解
    for i in range(index, len(nums)):
        subset.append(nums[i])
        dfs(nums, i+1, k-1, target-nums[i], subset, subsets)
        subset.pop()
nums = [1,2,3,4,6,7,8]
k, target = 2, 5
k_sum(nums, k, target)

 

posted @ 2022-08-02 09:44  今夜无风  阅读(88)  评论(0编辑  收藏  举报