leetcode(416). Partition Equal Subset Sum

本文探讨了一个经典的子集划分问题,即判断一个正整数数组是否可以被划分为两个子集,使每个子集的元素之和相等。通过将问题转化为0-1背包问题,我们提出了一种动态规划解决方案,并提供了详细的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem

Given a non-empty array containing only positive integers, find if the
array can be partitioned into two subsets such that the sum of
elements in both subsets is equal.

Note: Each of the array element will not exceed 100. The array size
will not exceed 200.

solution

这个问题可以转化为一个0-1背包问题,能否选出若干个数使得它们的和为sum(nums)/2。同时因为是“能否”而不是“最多”,因此可以在存储时使用bool值。

ps:动态规划时使用数组要比dict快,因为dict是接近 O(1) .

ps1:关于背包问题可以参考背包问题九讲

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = len(nums)
        s = sum(nums) 
        if s % 2:
            return False
        else:
            target = s // 2

        d = [[False]*(target+1) for _ in range(n)]
        for i in range(target+1):
            d[0][i] = True if i == nums[0] else False


        for i in range(1, n):#前i个物品
            for j in range(target+1):#重量不超过j
                d[i][j] = d[i-1][j] if j <= nums[i] else (d[i-1][j-nums[i]] or d[i-1][j])
            if d[i][target]:
                return True

        return d[n-1][target]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值