oneby7

Recursion and Backtracking Pick or skip

314. Count Subsequences with Sum K

Medium

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

Output: 4

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

Output: 3

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

Output: 3

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

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

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.

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.