2-D Dynamic Programming Knapsack
553. Count Subsets with Sum K
You are given an array of non-negative integers arr and a positive integer target. Count the subsets of
arr whose elements add up to exactly target.
A subset is a choice of some of the elements, by position. Two subsets are different if one of them has an element the other does not, even when the elements have equal values. So a 0 can be in a subset or left out, and the two choices count as two subsets.
The count can be very large, so return it modulo 109 + 7.
Example 1
Input: arr = [1, 2, 3, 3, 4], target = 6
4Explanation: The subsets are 2 + 4, 3 + 3, 1 + 2 + the first 3, and 1 + 2 + the second 3. The two 3s are different elements, so the last two subsets count separately.
Example 2
Input: arr = [0, 7, 0, 3], target = 7
4Explanation: Only the 7 makes 7. Each 0 can join it or stay out without changing the sum, so there are 2 × 2 = 4 subsets.
Example 3
Input: arr = [4, 6, 9], target = 12
0Explanation: The subsets add up to 4, 6, 9, 10, 13, 15 and 19. None of them is 12.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ arr.length ≤ 10000 ≤ arr[i] ≤ 1041 ≤ target ≤ 104
Clarifying questions
What you would ask an interviewer before writing any code.