You are given an array of positive integers nums and a positive integer k. Count the number of subsequences of nums whose selected elements sum to exactly k.
A subsequence is formed by choosing, for each index, whether to include that element exactly once or omit it. The chosen elements do not have to be contiguous. Two subsequences are different if their sets of chosen indices are different, so equal values at different indices count as distinct choices. Elements cannot be negated or given signs; each one is either added to the sum or left out.
Return the exact count as a 64-bit integer, with no modulo applied. The answer is guaranteed to be less than 2^50.
Function Signature
def count_subsequences(nums: list[int], k: int) -> int:
Rules
-
Subsequences are identified by their set of chosen indices, not by their values.
-
Because
k >= 1
, the empty subsequence never counts.
-
Return the exact count with no modulo.
Constraints
-
1 <= nums.length <= 50
-
1 <= nums[i] <= 10^4
-
1 <= k <= 10^4
-
The answer is less than
2^50
.
Examples
Input: nums = [5,5,1], k = 6
Output: 2
Indices {0, 2} give 5 + 1 = 6 and indices {1, 2} give 5 + 1 = 6. The two 5s are at different indices, so these count as 2 distinct subsequences.
Input: nums = [3,2,5,1,2,4], k = 5
Output: 5
The valid index sets are {0,1} (3+2), {0,4} (3+2), {2} (5), {3,5} (1+4) and {1,3,4} (2+1+2), for a total of 5.
Input: nums = [2,4,12], k = 5
Output: 0
Every element is even, so no selection can reach the odd target 5, and 12 is larger than k on its own.