416. Partition Equal Subset Sum
Asked at 14Amazon52Bloomberg49Google46Microsoft44Meta35Apple22eBay89Dream1168TikTok50Visa39tcs36Infosys30Goldman Sachs28Salesforce28
Problem
Decide whether nums (positive integers) can be split into two subsets with equal sums.
Example: [1,5,11,5] → true ([1,5,5] and [11]); [1,2,3,5] → false
Constraints: n ≤ 200; values ≤ 100.
Need a subset summing to total / 2. 0/1 knapsack over reachable sums: iterate the sum downward so each number is used once. (Python bitset trick: bits |= bits << x.)
Complexity: O(n · total/2).
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if total % 2:
return False
target = total // 2
dp = [True] + [False] * target
for x in nums:
for s in range(target, x - 1, -1):
dp[s] = dp[s] or dp[s - x]
return dp[target]
assert Solution().canPartition([1, 5, 11, 5]) is True
assert Solution().canPartition([1, 2, 3, 5]) is False
class Solution {
public boolean canPartition(int[] nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 == 1) return false;
int target = total / 2;
boolean[] dp = new boolean[target + 1];
dp[0] = true;
for (int x : nums)
for (int s = target; s >= x; s--) dp[s] |= dp[s - x];
return dp[target];
}
}
func canPartition(nums []int) bool {
total := 0
for _, x := range nums {
total += x
}
if total%2 == 1 {
return false
}
target := total / 2
dp := make([]bool, target+1) // dp[s]: some subset sums to s
dp[0] = true
for _, x := range nums {
for s := target; s >= x; s-- { // downwards so each number is used once
dp[s] = dp[s] || dp[s-x]
}
}
return dp[target]
}