分割等和子集

力扣题目链接: https://leetcode.cn/problems/partition-equal-subset-sum/submissions/679831040/

题目描述:

给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。

示例:

图片

思路:

关键在于问题转化,将原本判断是否可以均分问题,转换为空间为c = sum // 2的01背包问题,如果正好可以装得下一半容量的背包,那肯定可以均分。能想到这里,本题也就迎刃而解了。

附:

01背包问题链接:https://www.acwing.com/problem/content/2/
01背包问题题解:https://www.acwing.com/solution/content/1374/

代码:

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        total = sum(nums)
        if total % 2 != 0: return False
        n, c  = len(nums), total // 2
        num = [0] + nums
        f = [0] * (c + 1)
        for i in range(1, n + 1):
            for j in range(c, -1, -1): 
                if j >= num[i]:
                    f[j] = max(f[j - num[i]] + num[i], f[j])
        return True if f[c] == c else False
posted @ 2025-11-22 11:04  梨花满地  阅读(4)  评论(0)    收藏  举报