You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归中变量无法存储修改值:求目标组合数代码修复

问题:计算达成目标值的组合方式数量

我需要计算用列表元素组合出目标值的所有方式数量。现在递归的基准情况里已经更新了count变量,但返回时始终取初始值,希望只修改提供的代码,让它返回更新后的count值。

输入列表:[1,2,3]
目标值:3
预期输出:2(组合为[1,2]和[3])

原代码

def counter(ind,grid,target,count):
    if target==0:               #if target becomes 0(achieved)
        count+=1
        return count
    if ind==0:                      #if ind=0 is reached and target=value at that index(achieved)
        if target==grid[ind]:
            count+=1
            return count
        else:
            return

    nottake=counter(ind-1,grid,target,count)        #not taking the index's value
    take=0
    if target-grid[ind]>=0:                             #only if value at index is smaller that target
        take=counter(ind-1,grid,target-grid[ind],count)     #taking the index's value
    return count
grid=[1,2,3]
target=3
ind=len(grid)-1
print(counter(ind,grid,target,0))   #output should be 2 but i am getting 0

问题原因

递归调用时没有正确累加子函数返回的结果:Python中整数是不可变类型,递归里修改count不会影响上层函数的变量;同时部分分支返回None,导致后续无法正常累加。

修改后的代码

def counter(ind, grid, target, count):
    if target == 0:
        count += 1
        return count
    if ind == 0:
        if target == grid[ind]:
            count += 1
            return count
        else:
            return 0  # 不满足条件时返回0,避免None

    # 子调用返回None时默认取0
    nottake = counter(ind-1, grid, target, count) or 0
    take = 0
    if target - grid[ind] >= 0:
        take = counter(ind-1, grid, target - grid[ind], count) or 0
    # 返回两种选择的结果之和
    return nottake + take

grid = [1,2,3]
target = 3
ind = len(grid)-1
print(counter(ind, grid, target, 0))  # 输出2

修改说明

  1. 修正ind==0分支的返回值:不满足条件时返回0,而非None,确保后续累加不会出错
  2. 处理子调用的返回值:用or 0把None转换为0,避免累加时出现异常
  3. 最终返回nottake + take:合并“不取当前元素”和“取当前元素”两种情况的结果数量,而不是返回初始的count值

内容的提问来源于stack exchange,提问作者Sourya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:10:35