416. Partition Equal Subset Sum

本文探讨了如何判断一个仅包含正整数的非空数组能否被划分为两个子集,使这两个子集的元素之和相等。通过检查数组元素总和是否为偶数来快速排除不可能的情况,并运用动态规划解决核心问题。

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

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:

  1. Each of the array element will not exceed 100.
  2. The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

题意:

给出一个数组,判断是否可以分成两部分,使得他们的和相等。

思路:

先判断总和是否为偶数,奇数直接pass掉。然后求是否存在一个子数组的和为sum/2,此处利用到背包问题。判断背包是否可以恰好装满。

代码:

class Solution {
    public boolean canPartition(int[] nums) {
        int sum=0;
        int n=nums.length;
        for(int i=0;i<n;i++)
            sum+=nums[i];
        if(sum%2==1)
            return false;
        int []dp=new int[sum/2+1];
        dp[0]=0;
        for(int i=1;i<=sum/2;i++)
            dp[i]=Integer.MIN_VALUE;
        for(int i=n-1;i>=0;i--)
            for(int j=sum/2;j>=nums[i];j--)
            {
                dp[j]=Math.max(dp[j-nums[i]]+1,dp[j]);
                if(dp[sum/2]>0)
                    return true;
            }
        return dp[sum/2]>0;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值