Count Subset Sum
Given an array of positive numbers, find the total number of subsets whose sum is equal to a given number ‘S’.
Example 1:
Example 2:
Solution
This is similar to the Subset Sum problem. Basically, it's the same problem with the only difference that instead of returning whether there exists at least one subset with desired sum, we compute all such subsets.
We wil start with the code of Subset Sum Problem and will show how to transform the same code to achieve our end goal for this problem.
The only change we need to make is it to change our dp array from storing booleans to storing the count of subset sums at that index. So dp[i][j]
represents the count of subset sums with the first i items and the sum j.
When looping through the items and upto the sum, dp[i][j]
is equal to the count of subset sum we get by excluding the current item from the set + the count of subset sum by including the item in the set.
The code for the bottom up approach:
The following illustrations better help understand the DP table we store:
Space Optimization
Like in other problems of the 0/1 Knapsack Type, we can optimize space and just have a 1D array.
Last updated
Was this helpful?