Problems178
Search for a command to run...
How many subsequences add up to the target
Initialization
Every leaf that lands exactly on sum = 0 contributes 1. Counts are summed on the way back up, so the root ends up holding the total across the whole tree.
Take / Skip Recursion
1function func(ind, sum, nums) {2 // One valid subsequence3 if (sum === 0) return 1;4 5 // Overshot, or ran out of elements6 if (sum < 0 || ind === nums.length) return 0;7 8 // Include nums[ind]9 const take = func(ind + 1, sum - nums[ind], nums);10 11 // Exclude nums[ind]12 const notTake = func(ind + 1, sum, nums);13 14 return take + notTake;15}16 17function countSubsequenceWithTargetSum(nums, target) {18 return func(0, target, nums);//target: 319}