Overview
We want to find the number of ways to pick a subset of elements such that their sum equals K. This is a classic "pick or not pick" DP.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Count how many subsets of an array sum up exactly to a target K.
We want to find the number of ways to pick a subset of elements such that their sum equals K. This is a classic "pick or not pick" DP.
Let `dp[i][target]` be the number of subsets using the first `i` elements that sum to `target`.
For each element `nums[i]`, we either don't pick it (taking ways from `dp[i-1][target]`), or we do pick it (taking ways from `dp[i-1][target - nums[i]]`).
The total ways is the sum of ways from both decisions: `dp[i][target] = notPick + pick`. Base cases are crucial, especially handling 0s correctly.
| Num / Target | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 1 (idx 0) | 0 | 0 | 0 | 0 |
| 2 (idx 1) | 0 | 0 | 0 | 0 |
| 2 (idx 2) | 0 | 0 | 0 | 0 |
| 3 (idx 3) | 0 | 0 | 0 | 0 |