• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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:
Each of the array element will not exceed 100.
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.

Backpack problem: dp[i][j] means if the first i elements can sum up to value j

dp[i][j] = dp[i-1][j] || (j>=nums[i-1] && dp[i-1][j-nums[i-1]])

the result is if the half sum of the array can be summed up by elements in the array

 1 public class Solution {
 2     public boolean canPartition(int[] nums) {
 3         if (nums.length == 0) return true;
 4         int volume = 0;
 5         for (int num : nums) {
 6             volume += num;
 7         }
 8         if (volume % 2 == 1) return false;
 9         volume /= 2;
10         boolean[] dp = new boolean[volume+1];
11         dp[0] = true;
12         for (int i=1; i<=nums.length; i++) {
13             for (int j=volume; j>=0; j--) {
14                 dp[j] = dp[j] || (j>=nums[i-1] && dp[j-nums[i-1]]);
15             }
16         }
17         return dp[volume];
18     }
19 }

 

posted @ 2016-12-03 10:29  neverlandly  阅读(306)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3