Recursion and Backtracking Pick or skip
313. Does a Subsequence with Sum K Exist
You are given an array of integers nums and an integer k. Return true if some subsequence of nums
adds up to exactly k, and false otherwise.
A subsequence is any selection of elements from nums, kept in their original order. The chosen elements do
not have to be next to each other, and each element can be chosen at most once.
The subsequence must hold at least one element. The empty subsequence does not count, so for k = 0 you need
a real selection of one or more elements that adds up to 0.
Example 1
Input: nums = [6, -4, 9, 2, -5], k = 1
trueExplanation: Choosing 6 and −5, the first and the last elements, gives 6 + (−5) = 1. The elements between them are skipped.
Example 2
Input: nums = [3, 5, 1], k = 0
falseExplanation: Every element is positive, so every non-empty subsequence adds up to at least 1. Only the empty subsequence adds up to 0, and it does not count.
Example 3
Input: nums = [1000000000, 1000000000, -7, 1000000000]
k = 3000000000
trueExplanation: Skipping −7 leaves three values that add up to 3000000000. That is more than a 32-bit integer can hold.
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.