We need to decide whether the array nums can be split into two subsets with equal sum.
Core insight:
- Equivalent to checking if there exists a subset with sum =
total_sum / 2. - This is a classic 0/1 Knapsack DP problem.
- Define:
dp[j] = whether we can reach sum j. - Transition:
- For each number
num, update from right to left:
dp[j] = dp[j] || dp[j - num].
- For each number
- Compute total sum of
nums. If it's odd → impossible → returnfalse. - Set
target = sum / 2. - Initialize a DP array
dp[target+1]withdp[0] = true(sum 0 is always possible). - For each number
numinnums:- Iterate
jbackward fromtargettonum:- Update
dp[j] = dp[j] || dp[j - num].
- Update
- Iterate
- Answer is
dp[target].
- DP definition:
dp[j] = truemeans sumjcan be formed. - Why backward iteration? Prevents reusing the same number multiple times.
- Base case:
dp[0] = true. - Equivalent to: subset sum decision problem.
- Time:
O(n · target)n= number of elementstarget = sum / 2
- Space:
O(target)using 1D DP array.