SDE & MLE Prep

494. Target Sum

Problem

Put + or - in front of every number of nums and concatenate them into an expression. Count the expressions that evaluate to target.

Example: nums = [1,1,1,1,1], target = 3 → 5

Constraints: n ≤ 20; sum of nums ≤ 1000.

Let P = numbers with +. Then P − (total − P) = target ⇒ P = (total + target) / 2. Count subsets summing to P (0/1 knapsack, iterate downward).

Complexity: O(n · P).

class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        total = sum(nums)
        if abs(target) > total or (total + target) % 2:
            return 0
        P = (total + target) // 2
        dp = [1] + [0] * P
        for x in nums:
            for s in range(P, x - 1, -1):
                dp[s] += dp[s - x]
        return dp[P]