Count subsets with sum K
Pattern: Subsequences and knapsack
Count subsets that add up to k: the same table as subset sum, but holding counts. ways[s] += ways[s - x] for each item, looping s downwards. Zeros double the count, which this handles naturally.
The problem
Return the number of subsets of arr whose sum is k. The answer is taken modulo 10⁹ + 7.
Think first
- How does this differ from subset sum?
- What combine operation replaces OR?
- What does a 0 in the array do?
Hints
Brute force, and why it fails
Try all 2ⁿ subsets.
The key insight
Counts combine by addition, using exactly the same take-or-leave table.
Dry run
arr [2, 3, 5, 6, 8, 10], k = 10. ways[0] = 1 at the start.
Step 1 of 2
The plan
ways = [1, 0, ...]
for x: for s from k down to x: ways[s] += ways[s - x]
return ways[k]
Complexity
- Time
O(n × k)- Space
O(k)
One row of counts.
Edge cases
- k = 0 with zeros: 2^(number of zeros).
- No subset: 0.
- Large counts: modulo.
I've built my logic, show the code
Java
class Solution {
public int perfectSum(int[] arr, int k) {
final int MOD = 1_000_000_007;
int[] ways = new int[k + 1]; // ways[s]: subsets of the values so far adding up to s
ways[0] = 1;
for (int x : arr)
for (int s = k; s >= x; s--) ways[s] = (ways[s] + ways[s - x]) % MOD; // with x or without it
return ways[k];
}
}C++
class Solution {
public:
int perfectSum(vector<int>& arr, int k) {
const int MOD = 1000000007;
vector<int> ways(k + 1, 0); // ways[s]: subsets of the values so far adding up to s
ways[0] = 1;
for (int x : arr)
for (int s = k; s >= x; s--) ways[s] = (ways[s] + ways[s - x]) % MOD; // with x or without it
return ways[k];
}
};Python
class Solution:
def perfectSum(self, arr: list[int], k: int) -> int:
MOD = 1_000_000_007
ways = [1] + [0] * k # ways[s]: subsets of the values so far adding up to s
for x in arr:
for s in range(k, x - 1, -1):
ways[s] = (ways[s] + ways[s - x]) % MOD # with x or without it
return ways[k]Common mistakes
- Treating zeros specially and getting it wrong.
- Looping upwards.