Leetcode416. Partition Equal Subset Sum

文章讨论了如何使用0-1背包问题的方法解决给定整数数组能否划分为两部分,使两部分和相等的问题。通过定义动态规划状态dp来计算满足条件的最大和,若数组和为偶数则可成功划分,否则不可行。
摘要由CSDN通过智能技术生成

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].

这个问题可以转化为0-1背包问题,在这里重量和价值是一样的,因为我们求子数组的和。

定义状态dp[w]表示:从数组nums中选择一些元素,放入最多能装元素和为w的背包中得到的元素和最大为多少。如果最大和为w,即数组和的一半那么就可以分割。

class Solution:
    def zeroOnePackMethod(self, weight, value, W):
        size = len(weight)
        dp = [0 for _ in range(W+1)]
        for i in range(size+1):
            for w in range(W, w[i-1]-1, -1):
                dp[w] = min(dp[w], dp[w-weight[i-1]] + value[i-1])
        return dp[W]

    def canPartition(self, nums: List[int]) -> bool:
        if sum(nums) & 1:
            return False
        target = sum(nums)//2
        return self.zeroOnePackMethod(nums, nums, target)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值