【问题标题】:Using recursion, I'm getting an answer one less than the correct answer使用递归,我得到的答案比正确答案少一个
【发布时间】:2020-11-08 12:04:04
【问题描述】:

问题是:

给定一个包含所有正数且没有重复的整数数组,找出加起来为正整数目标的可能组合数。

例子:

nums = [1, 2, 3]
target = 4

可能的组合方式有:

(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

请注意,不同的序列被计为不同的组合。

因此输出为 7。

def combinationSum4(nums: List[int], target: int) -> int:
    if target == 0:
        return 1
    elif target < 0:
        return 0
    elif len(nums) == 0:
        return 1
    else:
        return combinationSum4(nums[1:], target-nums[0]) + combinationSum4(nums[1:], target)

输出是 7,但我得到的是 6。

【问题讨论】:

标签: python recursion


【解决方案1】:

我想介绍另一种通过递归来解决它的方法,看看这个:

m_nums = [1, 2, 3]
m_target = 4

def recursive_implementation(nums, target, cnt):
    if target == 0:
        return cnt+1
    else:
        for item in nums:
            if item<=target:
                cnt = recursive_implementation(nums, target-item, cnt)
    return cnt
                    

a = recursive_implementation(m_nums, m_target, 0)
print(a)

输出:

7

为了进行完整性检查,我也在输入端进行了尝试 - 1, 2 目标:4 选项是:

(1,1,1,1)
(1,1,2)
(1,2,1)
(2,1,1)
(2,2)
# output of the recursion - 5

【讨论】:

  • 非常感谢!
【解决方案2】:

我喜欢@YossiLevi 的一般方法,但我会避免他的额外论点并简单地这样做:

def combinationSum(numbers, target):
    if target == 0:
        return 1  # base case

    count = 0

    for number in numbers:
        if number <= target:
            count += combinationSum(numbers, target - number)

    return count

print(combinationSum([1, 2, 3], 4))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2018-05-30
    • 2018-05-28
    相关资源
    最近更新 更多