Problem
Given an integer arraynums, determine if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Each element must belong to exactly one of the two subsets.
Example 1
Input
nums = [1,5,11,5]
Output
true
Example 2
Input
nums = [1,2,3,5]
Output
false
Solution
This problem can be solved using Dynamic Programming with Memoization. First, we calculate the total sum of all elements. If the total sum is odd, it is impossible to divide the array into two subsets with equal sums.If the total sum is even, each subset must have a sum of
total / 2. Therefore, we need to determine whether we can select some elements whose sum is exactly this target.
At each index, we have two choices: skip the current element or take the current element. The state is represented by
(i, target), where i is the current index and target is the remaining sum we need to form.
If
target == 0, we have successfully formed the required subset. If we reach the end of the array or the target becomes negative, no valid subset can be formed.
The result for each
(i, target) state is stored in the memo array to avoid recalculating the same subproblem.
class Solution {
public boolean canPartition(int[] nums) {
int total = Arrays.stream(nums).sum();
if (total % 2 != 0)
return false;
Boolean[][] memo = new Boolean[nums.length][(total / 2) + 1];
return canPartition(nums, 0, total / 2, memo);
}
public boolean canPartition(
int[] nums, int i, int target, Boolean[][] memo) {
if (target == 0)
return true;
if (i >= nums.length || target < 0)
return false;
if (memo[i][target] != null)
return memo[i][target];
return memo[i][target] =
canPartition(nums, i + 1, target, memo) ||
canPartition(nums, i + 1, target - nums[i], memo);
}
}
Complexity
There aren × target possible states, where target = total / 2. Each state is calculated only once, so the time complexity is O(n × target).
The memoization array stores
O(n × target) states, and the recursion stack can grow up to O(n). Therefore, the extra space complexity is O(n × target).
Comments
No comments yet. Ask a question or share what helped.