如何在递归 python 函数中冒泡一个数组?

乘风 python 230

原文标题How can i bubble up an array in a recursive python function?

我正在学习动态编程,我正在观看的视频显示了 JS 中的问题的解决方案,如下所示:

enter image description here

我想弄清楚如何用 Python 编写这个解决方案,我已经制作了这样的递归函数:

def howSum(nums: List[int], target: int):

    if target == 0:
        return []
    elif target < 0:
        return None

    for num in nums:
        rem = target - num
        res = howSum(nums, rem)

        if res:
            res.append(num)
            return res

    return None

print(howSum([2,3,5], 8))

但是我的函数返回Noneinstad返回数组[2,2,2,2]

将此函数从 JS 转换为 Python 时我做错了什么吗?

原文链接:https://stackoverflow.com//questions/71462512/how-can-i-bubble-up-an-array-in-a-recursive-python-function

回复

我来回复
  • SuperStormer的头像
    SuperStormer 评论

    空数组在Python中是假的,所以if res应该是if res is not None(为了匹配JS中的对应条件)。

    2年前 0条评论