资讯专栏INFORMATION COLUMN

leetcode 416 Partition Equal Subset Sum

jsummer / 547人阅读

摘要:如果是奇数的话,那一定是不满足条件的,可以直接返回。如果是偶数,将除获得我们要求的一个子数组元素的和。如何暂存我们计算的中间结果呢声明一个长度为的布尔值数组。每个元素的布尔值代表着,数组中是否存在满足加和为的元素序列。

题目详情
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. 

题目的意思是输入一个非空的、只含正整数的数组nums,要求我们判断,数组nums能否被分成两个子数组,满足两个子数组的和相等。

例1:
输入: [1, 5, 11, 5]
输出: true
解释: 输入数组可以被分为[1, 5, 5]和[11].
例2:
输入: [1, 2, 3, 5]
输出: false
解释: 数组无法被拆分成两个和相等的子数组.

想法

首先我们需要遍历一趟得到整个数组的和sum,从而求出每个子数组元素的加和(sum/2)。

如果sum是奇数的话,那一定是不满足条件的,可以直接返回false。如果sum是偶数,将sum除2获得我们要求的一个子数组元素的和。

如何暂存我们计算的中间结果呢?

声明一个长度为sum+1的布尔值数组res。每个元素的布尔值res[i]代表着,数组中是否存在满足加和为i的元素序列。

对于每一个元素,我们都要求出他以及前面遍历过的元素所组合出的元素和。

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71023.html

相关文章

  • leetcode416. Partition Equal Subset Sum

    摘要:题目要求假设有一个全为正整数的非空数组,将其中的数字分为两部分,确保两部分数字的和相等。而这里的问题等价于,有个物品,每个物品承重为,问如何挑选物品,使得背包的承重搞好为所有物品重量和的一般。 题目要求 Given a non-empty array containing only positive integers, find if the array can be partitio...

    Caicloud 评论0 收藏0
  • [LeetCode] 416. Partition Equal Subset Sum

    Problem 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 ...

    makeFoxPlay 评论0 收藏0
  • [Leetcode - Dynamic Programming] Partition Equal S

    摘要:背包问题假设有个宝石,只有一个容量为的背包,且第个宝石所对应的重量和价值为和求装哪些宝石可以获得最大的价值收益思路我们将个宝石进行编号,寻找的状态和状态转移方程。我们用表示将前个宝石装到剩余容量为的背包中,那么久很容易得到状态转移方程了。 Partition Equal Subset Sum Given a non-empty array containing only posi...

    qpal 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0
  • [LeetCode] 698. Partition to K Equal Sum Subsets

    Problem Given an array of integers nums and a positive integer k, find whether its possible to divide this array into k non-empty subsets whose sums are all equal. Example 1:Input: nums = [4, 3, 2, 3,...

    kuangcaibao 评论0 收藏0

发表评论

0条评论

jsummer

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<