LeetCode 416 - Partition Equal Subset Sum
LeetCode 416 - Partition Equal Subset Sum
Table of Contents
Problem Statement
Given an integer array nums
, return true
if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false
otherwise.
Using Dynamic Programming
To solve the problem of partitioning the array into two subsets with equal sums, we can use dynamic programming (DP).
Sum Calculation:
- Calculate the total sum of the array using a loop.
- If the sum is odd, return
false
immediately since it canβt be split evenly.
Subset Sum Reduction:
- Set
target = totalSum / 2
. Now, we need to determine if there exists a subset whose elements sum totarget
.
- Set
Dynamic Programming Array:
- Initialize a boolean DP array of size
target + 1
, wheredp[i]
means βis a subset sum ofi
achievable?β - Set
dp[0] = true
(a sum of 0 is always achievable). - For each number in
nums
, update the DP array in reverse to avoid using the same number multiple times.
- Initialize a boolean DP array of size
Final Check:
- If
dp[target]
istrue
, then such a subset exists, and partitioning is possible.
- If
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
bool canPartition(vector<int>& nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
if (totalSum % 2 != 0) return false;
int target = totalSum / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int num : nums) {
for (int i = target; i >= num; i--) {
dp[i] = dp[i] || dp[i - num];
}
}
return dp[target];
}
};
Complexity
Time Complexity: π(π Γ target)
- Where π is the size of
nums
andtarget = totalSum / 2
. - The outer loop iterates over
nums
, and the inner loop iterates up totarget
.
Space Complexity: π(target)
- The DP array stores information about achievable subset sums.
Conclusion
This implementation efficiently checks for partitioning conditions, leveraging dynamic programming to handle large arrays and sums.