leetcode 416. Partition Equal Subset Sum(分割等和子集)

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.

Example 1:

Input: [1, 5, 11, 5]

Output: true

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

给出一个数组,问能不能把数组分割成两个子集,使每个子集的和为数组全部元素和的一半。
数组元素都是正整数。

思路:
因为元素都是正整数,所以子集的和也是正整数,意味着原整个数组的和(子集的和 * 2)应该是偶数。
因此原数组的和为奇数时直接返回false.

假设原数组元素的和是sum,定义长度为sum+1的DP数组,表示数组中选取元素能不能构成sum的和,也就是来了一个元素,把它和上一步所有可能的和相加,得到新的所有可能的和。
为了节省space空间,把二维DP数组压缩到一维,从右往左访问DP数组,这样就不至于重复访问数组中的元素。
每次遍历一遍DP,看sum/2处是否为true,为true时直接返回。

    public boolean canPartition(int[] nums) {
        if(nums == null || nums.length == 0) {
            return false;
        }
        
        int sum = 0;
        
        for(int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        if(sum % 2 == 1) {
            return false;
        }
        
        boolean[] dp = new boolean[sum + 1];
        dp[0] = true;
        
        for(int num : nums) {
            for(int i = sum; i >= 0; i--) {
                if(dp[i]) {
                    dp[i + num] = true;
                }
            }
            if(dp[sum/2]) {
                return true;
            }
        }
        return false;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值