oneby7

2-D Dynamic Programming Knapsack

553. Count Subsets with Sum K

Medium

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

Output: 4

Explanation: 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

Output: 4

Explanation: 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

Output: 0

Explanation: 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.

arr = [1, 1, 1], target = 2

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 0 ≤ arr[i] ≤ 104
  • 1 ≤ target ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.