Recursion and Backtracking Pick or skip
314. Count Subsequences with Sum K
You are given an array of integers nums and an integer k. Return the number of non-empty
subsequences of nums whose elements add up to exactly k.
A subsequence keeps some of the elements, at least one, and drops the rest. The elements it keeps do not
have to be next to each other. Two subsequences are different when they use different positions, even if
they hold the same values. So in [3, 3], the first 3 on its own and the second 3 on its own are two
different subsequences.
Example 1
Input: nums = [3, 1, -2, 4, 2], k = 4
4Explanation: Four subsequences add up to 4: [3, 1], [4], [3, 1, -2, 2] and [-2, 4, 2].
Example 2
Input: nums = [5, 5, 5], k = 10
3Explanation: Any two of the three 5s add up to 10. The pairs use positions 0 and 1, 0 and 2, and 1 and 2, so they are three different subsequences.
Example 3
Input: nums = [0, 3, -3], k = 0
3Explanation: [0], [3, -3] and [0, 3, -3] add up to 0. The empty subsequence also has a sum of 0, but it does
not count.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 20-109 ≤ nums[i] ≤ 109-2 × 1010 ≤ k ≤ 2 × 1010
Clarifying questions
What you would ask an interviewer before writing any code.