Python实现【MELON的难题】

360影视 欧美动漫 2025-04-18 10:48 2

摘要:def can_partition_min_stones:n = int(input)stones = list(map(int, input.split))total = sum(stones)if total % 2 != 0:print(-1)retur

def can_partition_min_stones:n = int(input)stones = list(map(int, input.split))total = sum(stones)if total % 2 != 0:print(-1)returntarget = total // 2dp = [float('inf')] * (target + 1)dp[0] = 0 # 达到重量0需要0块石头for stone in stones:for w in range(target, stone - 1, -1):if dp[w - stone] + 1 总重量检查:如果所有石头的总重量 total 不是偶数,直接返回 -1。目标重量:目标是找到一个子集,其重量为 target = total / 2。最少石头数量:在所有可能的子集中,找到重量为 target 且包含最少石头的子集。

来源:弘霖教育

相关推荐