Target Sum

medium array dp backtracking

Problem

You are given an integer array nums and an integer target. Build expressions by adding '+' or '−' in front of each integer. Return the number of expressions that evaluate to target.

Inputnums = [1, 1, 1, 1, 1], target = 3
Output5
Let P = sum of '+' subset. Then 2·P − total = target, so P = (target + total)/2. Count subsets summing to P.

def find_target_sum_ways(nums, target):
    total = sum(nums)
    if (target + total) % 2 or abs(target) > total: return 0
    p = (target + total) // 2
    dp = [0] * (p + 1)
    dp[0] = 1
    for x in nums:
        for s in range(p, x - 1, -1):
            dp[s] += dp[s - x]
    return dp[p]
function findTargetSumWays(nums, target) {
  const total = nums.reduce((a, b) => a + b, 0);
  if ((target + total) % 2 !== 0 || Math.abs(target) > total) return 0;
  const p = (target + total) / 2;
  const dp = new Array(p + 1).fill(0);
  dp[0] = 1;
  for (const x of nums) {
    for (let s = p; s >= x; s--) dp[s] += dp[s - x];
  }
  return dp[p];
}
class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        int total = 0; for (int x : nums) total += x;
        if (((target + total) & 1) != 0 || Math.abs(target) > total) return 0;
        int p = (target + total) / 2;
        int[] dp = new int[p + 1];
        dp[0] = 1;
        for (int x : nums)
            for (int s = p; s >= x; s--) dp[s] += dp[s - x];
        return dp[p];
    }
}
int findTargetSumWays(vector<int>& nums, int target) {
    int total = accumulate(nums.begin(), nums.end(), 0);
    if (((target + total) & 1) || abs(target) > total) return 0;
    int p = (target + total) / 2;
    vector<int> dp(p + 1, 0);
    dp[0] = 1;
    for (int x : nums)
        for (int s = p; s >= x; s--) dp[s] += dp[s - x];
    return dp[p];
}
Time: O(n · P) where P = (target + total)/2 Space: O(P)