Algo-Sim › Dynamic Programming

Target Sum

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Put + or − before each number to hit a target. Algebra turns it into counting subsets with sum (total + target) / 2.

Problem

Given an integer array nums and an integer target, put a + or a - in front of every number and add them all up. Return the number of different sign choices whose result equals target.

Constraints

Edge cases to test

Follow-up questions

How does the algebra work?
If P is the plus-set, P − (total − P) = target, so P = (total + target)/2: count subsets with that sum, O(n·sum).
Is memoised DFS fine?
Memoise on (index, running sum): O(n·sum) states, the same cost with more overhead.

Solution

Java

public int findTargetSumWays(int[] nums, int target) {
    int total = 0;
    for (int x : nums) total += x;
    if (Math.abs(target) > total || (total + target) % 2 != 0) return 0;
    int p = (total + target) / 2, n = nums.length;
    int[][] dp = new int[n + 1][p + 1];
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++) {
        for (int s = 0; s <= p; s++) {
            dp[i][s] = dp[i - 1][s];
            if (nums[i - 1] <= s) dp[i][s] += dp[i - 1][s - nums[i - 1]];
        }
    }
    return dp[n][p];
}

Python

def find_target_sum_ways(nums, target):
    total = sum(nums)
    if abs(target) > total or (total + target) % 2 != 0:
        return 0
    p, n = (total + target) // 2, len(nums)
    dp = [[0] * (p + 1) for _ in range(n + 1)]
    dp[0][0] = 1
    for i in range(1, n + 1):
        for s in range(p + 1):
            dp[i][s] = dp[i - 1][s]
            if nums[i - 1] <= s:
                dp[i][s] += dp[i - 1][s - nums[i - 1]]
    return dp[n][p]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int findTargetSumWays(vector<int> &nums, int target) {
        int total = 0;
        for (int x : nums)
            total += x;
        if (abs(target) > total || (total + target) % 2 != 0)
            return 0;
        int p = (total + target) / 2, n = int(nums.size());
        vector<vector<int>> dp = vector<vector<int>>(n + 1, vector<int>(p + 1));
        dp[0][0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int s = 0; s <= p; s++) {
                dp[i][s] = dp[i - 1][s];
                if (nums[i - 1] <= s)
                    dp[i][s] += dp[i - 1][s - nums[i - 1]];
            }
        }
        return dp[n][p];
    }
};

More Dynamic Programming problems