Skip to content

ディープテック経済

市場が追いついたら、もう遅い。

Menu
Menu

用Python解决分区背包问题

Posted on 2023年1月30日 by DeepRecommend

def partition_problem(nums, n):
    def knapsack(nums, n, total):
        dp = [0] * (total + 1)
        for i in range(n):
            for j in range(total, nums[i] - 1, -1):
                dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])
        return dp[total]

total = sum(nums)
    if total % 2 != 0:
        return False
    total //= 2
    return knapsack(nums, n, total) == total

nums = [1, 5, 11, 5]
n = len(nums)
if partition_problem(nums, n):
    print("Can be divided into two subsets of equal sum")
else:
    print("Can't be divided into two subsets of equal sum")

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

分类

  • アーカイブ (22)

归档

  • 2023 年 4 月 (7)
  • 2023 年 3 月 (5)
  • 2023 年 2 月 (9)
  • 2023 年 1 月 (57)
  • 2022 年 12 月 (8)
  • 2022 年 11 月 (1)
© 2026 ディープテック経済 | Powered by Minimalist Blog WordPress Theme