美文网首页算法代码
分割等和子集

分割等和子集

作者: windUtterance | 来源:发表于2020-11-10 09:03 被阅读0次

题目描述
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。

示例
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].

Java代码

class Solution {
    public boolean find(int[] nums, int target, int index) {
        if(target == 0) return true;
        for(int i = index;i < nums.length;i++) {
            if(i > index && nums[i] == nums[i - 1]) continue;
            if(target - nums[i] < 0) return false;
            if(find(nums, target - nums[i], i + 1)) return true;
        }
        return false;
    }

    public boolean canPartition(int[] nums) {
        int total = 0;
        for(int num : nums) total += num;
        Arrays.sort(nums);
        if((total & 1) == 1) return false;
        if(total == 0) return true;
        return find(nums, total / 2, 0);
    }

    public boolean canPartition(int[] nums) {
        int len = nums.length;
        if(len == 0) return false;

        int sum = 0;
        for(int num : nums) sum += num;
        if((sum & 1) == 1) return false;

        int target = sum / 2;
        boolean[] dp = new boolean[target + 1];
        dp[0] = true;

        if(nums[0] <= target) dp[nums[0]] = true;
        for(int i = 1;i < len;i++) {
            for(int j = target;nums[i] <= j;j--) {
                if(dp[target]) return true;
                dp[j] = dp[j] || dp[j - nums[i]];
            }
        } 
        return dp[target];
    }
}

相关文章

  • 分割等和子集

    题目描述:给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 示例:输入...

  • 分割等和子集

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/part...

  • 分割等和子集

    求未知个数组中的数的组合,不重复使用的情况下求和为k的解是否存在。

  • 分割等和子集

    分割等子集[https://programmercarl.com/0416.%E5%88%86%E5%89%B2%...

  • 分割等和子集

    第一版代码: 只用一维数组解决 参考动态规划|分割等和子集 - 知乎 (zhihu.com)[https://zh...

  • 0/1背包问题 0/1 Knapsack

    题目列表 相等子集划分问题 Equal Subset Sum Partition 416. 分割等和子集 子集和问...

  • 416. 分割等和子集

    给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 注意: 每个数组中的...

  • 416. 分割等和子集

  • 416. 分割等和子集

  • 416. 分割等和子集

    一 题目: 二 思路: 背包问题 状态定义:dp[i][j]表示从数组的 [0, i] 这个子区间内挑选一些正整数...

网友评论

    本文标题:分割等和子集

    本文链接:https://www.haomeiwen.com/subject/jefbektx.html