Count all subsequences with sum K

Pattern: Subsequences with sum

medium

The number of subsequences with sum k is the number that take the first value (and need k minus it from the rest) plus the number that skip it. Recurse on that, stopping when the remainder goes negative.

The problem

Given an array of positive whole numbers and k, return how many non-empty subsequences add up to exactly k. Elements at different positions count as different, even if their values are equal. For example, [4, 9, 2, 5, 1] with k = 10 gives 2 (9 + 1 and 4 + 5 + 1).

The function name countSubsequenceWithTargetSum matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • How does "count" change the combine step compared with "does one exist"?
  • When does a branch count as one?
  • Can the empty subsequence ever count here?

Hints

    Brute force, and why it fails

    Check all 2ⁿ subsets: O(2ⁿ × n). The recursion is O(2ⁿ). For larger n with small k, a DP table of counts by sum is O(n × k).

    The key insight

    Counting splits cleanly into disjoint cases, take or skip, so the answers simply add. This is the same tree as the yes/no version, with + instead of or.

    Dry run

    left10

    nums = [4, 9, 2, 5, 1] and k = 10.

    Step 1 of 4

    The plan

    function count(i, left):
        if left < 0: return 0
        if i == n: return 1 if left == 0 else 0
        return count(i + 1, left - a[i]) + count(i + 1, left)
    return count(0, k)
    

    Complexity

    Time
    O(2ⁿ)
    Space
    O(n)

    Two branches per element, n deep.

    Edge cases

    • No subsequence works: 0.
    • Equal values, as in [1, 1, 1] with k = 2: 3, one for each pair of positions.
    • k equal to the whole sum: at least 1.
    I've built my logic, show the code

    Java

    class Solution {
        public int countSubsequenceWithTargetSum(int[] nums, int k) {
            return count(nums, 0, k);
        }
    
        private int count(int[] nums, int i, int left) {
            if (left < 0) return 0;                         // values are positive: overshooting can never come back
            if (i == nums.length) return left == 0 ? 1 : 0;
            return count(nums, i + 1, left - nums[i])       // subsequences that take nums[i]
                 + count(nums, i + 1, left);                // plus those that skip it
        }
    }

    C++

    class Solution {
    public:
        int countSubsequenceWithTargetSum(vector<int>& nums, int k) {
            return count(nums, 0, k);
        }
    
        int count(vector<int>& nums, size_t i, int left) {
            if (left < 0) return 0;                         // values are positive: overshooting can never come back
            if (i == nums.size()) return left == 0 ? 1 : 0;
            return count(nums, i + 1, left - nums[i])       // subsequences that take nums[i]
                 + count(nums, i + 1, left);                // plus those that skip it
        }
    };

    Python

    class Solution:
        def countSubsequenceWithTargetSum(self, nums: list[int], k: int) -> int:
            def count(i: int, left: int) -> int:
                if left < 0:
                    return 0                        # values are positive: overshooting can never come back
                if i == len(nums):
                    return 1 if left == 0 else 0
                return count(i + 1, left - nums[i]) + count(i + 1, left)   # take nums[i], plus skip it
    
            return count(0, k)

    Common mistakes

    • Returning 1 as soon as left reaches 0 when the array may contain zeros, which misses the subsequences that also take those zeros.
    • Counting distinct value sets instead of positions.
    • Using or instead of +.

    Similar problems