首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最小子集差码显示错误输出

最小子集差码显示错误输出
EN

Stack Overflow用户
提问于 2022-01-22 06:46:15
回答 1查看 51关注 0票数 -1

我的最小子集差代码(将一个子集划分为两个子集,使子集和的差最小)显示的输出错误,我不明白怎么做。我经历了所有的事情,仍然无法理解。请帮助我解决这个问题!!

示例

arr[] = {1,2,7}

产出:4

说明: Subset1 = {1,2},Subset1 = 3,Subset2 = {7},Subset2 =7

结果是7-3 =4。

这里是我的代码

代码语言:javascript
复制
import sys

def subset_sum(arr, n, S, dp):
    # If sum is 0, then answer is 1
    if(S==0):
        return 1

    # If sum is not 0 and set is empty,
    # then answer is 0
    if(n==0):
        return 0

    # If the value is not -1 it means it
    # already call the function
    # with the same value.
    # it will save our from the repetition.
    if(dp[n-1][S]!=-1):
        return dp[n-1][S]

    # if the value of a[n-1] is
    # greater than the sum.
    # we call for the next value
    if(S<arr[n-1]):
        dp[n-1][S] = subset_sum(arr, n-1, S, dp)

    else:
        # Here we do two calls because we
        # don't know which value is
        # full-fill our criteria
        # that's why we doing two calls
        dp[n-1][S] = subset_sum(arr, n-1, S, dp) or subset_sum(arr, n-1, S-arr[n-1], dp)
    return dp[n-1][S]

def minimum_subset_diff(arr, n):
    S = 0

    # Calculate sum of all elements
    for i in range(n):
        S += arr[i]
    
    # Create an 2d list to store
    # results of subproblems
    global dp
    dp = [[-1 for _ in range(S+1)] for _ in range(n+1)]

    # Fill the partition table
    # using memoization approach
    subset_sum(arr, n, S, dp)

    # Find the largest i such that dp[n][i]
    # is true where i loops from S (sum) t0 0
    diff = sys.maxsize
    for i in range(S):
       if  dp[n][i] == 1:
           
           # if S has partition of s1 and s2
           # then difference is s2-s1 => (S-s1)-s1 => S-2s1
           # hence, S-2*i is formed
           # and here we take absolute value
           if(abs(S-2*i) < diff):
               diff = abs(S-2*i)

    return diff

# Driver Code  
if __name__ == '__main__':
    arr = [1, 2, 7]
    n = len(arr)
    print(minimum_subset_diff(arr, n))

输出

代码语言:javascript
复制
9223372036854775807

预期输出

代码语言:javascript
复制
4
EN

回答 1

Stack Overflow用户

发布于 2022-01-22 08:03:48

你犯了一个错误。我不完全理解为什么您将subset_sum(arr, n, S, dp)的值缓存在dp[n-1, S]而不是dp[n, S]中,这对我来说更自然,但这就是您要做的。

但是,在稍后检查数组时,您会忘记这一点。在后面的代码中,您看错了行。

当您重写代码时,请查看数组dp。它是否包含你期望它包含的内容?如果您看过了,就会注意到整个最后一行是-1,您只需返回sys.max,因为条件永远不满足。

我强烈建议您查看@cache的文档。让Python为您做这个缓存,而不是自己做。这类问题就会消失。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70810615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档