Count Subsets with Sum K

Implement countSubsetsWithSumK

Given an array of non-negative integers and a target amount k, count how many distinct subsets — distinguished by which positions are chosen, not just which values appear — sum to exactly k. Two equal-valued numbers sitting at different positions in the array count as different elements, so choosing one versus the other produces two separate subsets even though their sums are identical. Just like checking whether any subset reaches a target, every number here faces the same include-or-exclude choice — but now both branches need to be counted, not just checked, since each one might contribute one or more valid ways. The recursion can't stop the instant the running total hits the target, either: a later zero-valued number, for example, can still be freely included or excluded without changing the sum, and each of those is a genuinely different subset. So the tally only happens once every number has been decided on, and the total number of ways is simply the ways found by excluding a number plus the ways found by including it, added together at every step.

Example 1:

Input: nums = [3,4,4,7], k = 7

Output: 3

Example 2:

Input: nums = [2,2,2,2], k = 4

Output: 6

Example 3:

Input: nums = [6,6,6], k = 12

Output: 3

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 20
  • 0 ≤ nums[i] ≤ 100
  • 0 ≤ k ≤ 1000

nums =

[3, 4, 4, 7]

k =

7