416. 分割等和子集:贪心+动态规划

https://leetcode.cn/problems/partition-equal-subset-sum/

题目要求

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

贪心

class Solution {
    boolean flag = false;

    public boolean canPartition(int[] nums) {
        int n = nums.length;
        int total = 0;
        for (int i = 0; i < n; i++) {
            total += nums[i];
        }
        if (total % 2 != 0)
            return false;
        backtrack(0, nums, total / 2);
        return flag;
    }

    public void backtrack(int index, int[] nums, int target) {
        if (target < 0)
            return;
        if (target == 0) {
            flag = true;
            return;
        }
        for (int i = index; i < nums.length; i++) {
            backtrack(i + 1, nums, target - nums[i]);
        }
    }
}
  • 本题使用贪心会超时

动态规划

class Solution {
    public boolean canPartition(int[] nums) {
        if (nums == null || nums.length == 0)
            return false;
        int n = nums.length;
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        if (total % 2 != 0)
            return false;
        int target = total / 2;
        int[] dp = new int[target + 1];
        for (int i = 0; i < n; i++) {
            for (int j = target; j >= nums[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
            }
        }
        return dp[target] == target;
    }
}
  • 01背包相对于本题,主要要理解,题目中物品是nums[i],重量是nums[i],价值也是nums[i],背包体积是sum/2。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值