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:

  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表示,这个数是否是可达的
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];
}
和题目494解法一样
posted @   MarkLeeBYR  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示