416. Partition Equal Subset Sum
https://leetcode.com/problems/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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean canPartition(int[] nums) { | |
int sum = 0; | |
for (int num: nums) { | |
sum += num; | |
} | |
if (sum % 2 == 1) { | |
return false; | |
} | |
Boolean[][] memo = new Boolean[nums.length][1 + sum / 2]; | |
return dfs(nums, 0, 0, sum / 2, memo); | |
} | |
private boolean dfs(int[] nums, int i, int prefix, int target, Boolean[][] memo) { | |
if (i == nums.length) { | |
return prefix == target; | |
} | |
if (memo[i][prefix] != null) { | |
return memo[i][prefix]; | |
} | |
boolean ans = false; | |
// include current element, only if inclusion is valid | |
if (prefix + nums[i] <= target) { | |
ans = dfs(nums, i + 1, prefix + nums[i], target, memo); | |
} | |
// skip current element | |
ans = ans || dfs(nums, i + 1, prefix, target, memo); | |
memo[i][prefix] = ans; | |
return ans; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean canPartition(int[] nums) { | |
int sum = 0; | |
for (int num: nums) { | |
sum += num; | |
} | |
if (sum % 2 == 1) { | |
return false; | |
} | |
return dfs(nums, 0, 0, sum / 2); | |
} | |
private boolean dfs(int[] nums, int i, int prefix, int target) { | |
if (i == nums.length) { | |
return prefix == target; | |
} | |
boolean ans = false; | |
// include current element, only if inclusion is valid | |
if (prefix + nums[i] <= target) { | |
ans = dfs(nums, i + 1, prefix + nums[i], target); | |
} | |
// skip current element | |
ans = ans || dfs(nums, i + 1, prefix, target); | |
return ans; | |
} | |
} |