Dynamic Programming21 sections · 916 units
Open in Course

Practice - Subset Sum Count

Apply counting pattern

Practice problem: given an array of positive integers and a target sum SS, count how many subsets sum exactly to SS. This is the counting version of Partition.

Let dp[s]dp[s] = number of subsets summing to ss. Base case: dp[0]=1dp[0] = 1 (empty subset). Transition: for each element xx, update dp[s]=dp[s]+dp[sx]dp[s] = dp[s] + dp[s-x] for ss from target down to xx. Try it on [1,2,3,4,5][1, 2, 3, 4, 5] with target 55. Expected answer: 33 subsets ({5}\{5\}, {1,4}\{1,4\}, {2,3}\{2,3\}).