【问题标题】:Getting all possible combinations for powersum problem获取 powersum 问题的所有可能组合
【发布时间】:2021-08-17 22:10:51
【问题描述】:

我试图找出构成幂和的所有数字组合。下面是我的代码,它在找到第一个组合后返回。

`代码:

def powerSum(targetSum, N):
    def helper(x,n,c):
        if pow(c,n)==x:
            return [c]
        if pow(c,n)>x:
            return None
        l = helper(x,n,c+1)
        r = helper(x-pow(c,n),n,c+1)
        if l!=None or r!=None:
            if l==None:
                return r+[c]
            else:
                return l
    return helper(targetSum,N,1)
print(powerSum(100,2))

有人可以帮我返回所有可能的组合吗 例子: 如果输入是 targetSum =100 并且 N=2 输出应该是三个可能的组合列表的列表 =[[10],[6,8][1,3,4,5,7]] 我的输出只有 [10]

【问题讨论】:

    标签: python recursion dynamic-programming


    【解决方案1】:

    重新考虑返回类型:

    def powerSum(targetSum, N):
        def helper(x, n, c):
            if pow(c, n) == x:
                return [[c]]
    
            if pow(c, n) > x:
                return []
    
            l = helper(x, n, c + 1)
            r = helper(x - pow(c, n), n, c + 1)
    
            for _r in r:
                l.append([c] + _r)
    
            return l
    
        return helper(targetSum, N, 1)
    
    print(powerSum(100, 2))
    

    【讨论】:

    • 不错的解决方案。可能要加cmets来阐述原代码问题?
    • @DanielHao 谢谢。我以为我做到了——它与 OP 基本相同,只是返回类型不同(因此也对这些类型进行了处理)。
    • 非常感谢您的解决方案,我对递归以及如何处理返回类型和所有内容有点陌生。我很想提出改善自己的建议
    猜你喜欢
    • 2013-10-06
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多