首页 > 其他分享 >416.Partition Equal Subset Sum

416.Partition Equal Subset Sum

时间:2023-03-16 17:37:10浏览次数:47  
标签:Subset nums int sum Partition 416 boolean array dp

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.


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


标签:Subset,nums,int,sum,Partition,416,boolean,array,dp
From: https://www.cnblogs.com/MarkLeeBYR/p/17223485.html

相关文章

  • 算法随想Day37【动态规划】| LC416-分割等和子集
    动态规划五部曲确定dp[i]的含义dp递推公式dp数组如何初始化确认dp数组遍历顺序打印dp数组,主要用于调试LC416.分割等和子集这道题是“背包问题”的应用,但其实不好......
  • 《Spectral Partitioning Residual Network With Spatial Attention Mechanism for Hy
    论文作者:XiangrongZhang,ShouwangShang,XuTang,etal.论文发表年份:2021模型简称:SPRN发表期刊:IEEETransactionsonGeoscienceandRemoteSensing论文链接:Sci-Hub......
  • 86. Partition List
    ##题目Givenalinkedlistandavaluex,partitionitsuchthatallnodeslessthanxcomebeforenodesgreaterthanorequaltox.Youshouldpreservethe......
  • hutool XML反序列化漏洞(CVE-2023-24162)
    漏洞简介Hutool中的XmlUtil.readObjectFromXml方法直接封装调用XMLDecoder.readObject解析xml数据,当使用readObjectFromXml去处理恶意的XML字符串时会造成任意代......
  • 动态规划(8)、416. 分割等和子集
    题目链接:416.分割等和子集-力扣(LeetCode) ......
  • MogDB 学习笔记之 --exchange partition
    #概念描述MogDB提供了从分区交换的功能,如单表转化到一个分区中基本语法:ALTERTABLE...EXCHANGEPARTITION数据库版本#测试验证##1、环境准备```miao=>selectversio......
  • P4416 [COCI2017-2018#1] Plahte 题解
    题意简述:给定\(n\)个互不相交,可以重叠的矩阵,对某些点染色,这个点上的所有矩阵会被染上这个颜色,求最后每个矩阵会有多少种颜色。解:我们可以先把矩阵拆成上下两条水平线......
  • P5416 [CTSC2016]时空旅行 题解
    首先题中的\(y,z\)好像没啥用……首先对于每一次询问,要求\(\min((x_0-x_i)^2+c_i)\)设\((x_0-x_i)^2+c_i=ans\)。那么\(x_0^2+x_i^2-2x_0x_i+c_i=ans\)所以\(x_0......
  • [AtCoder] F - Knapsack for All Subsets
    ProblemStatement dp[i][j]:thenumberofsubsetsofA[0,i]whosesumisj.dp[0][0]=1,thereisonly1wayofnotpickinganythingfromanemptyarrayt......
  • The Number of Good Subsets
    TheNumberofGoodSubsetsYouaregivenanintegerarray nums .Wecallasubsetof nums good ifitsproductcanberepresentedasaproductofoneormo......