AlgoMaster Logo

Target Sum

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Backtracking

The first approach uses recursion to explore all possible ways to add or subtract numbers from the array to achieve the target sum.

Intuition:

For each number in the array, you have two choices:

  • Add it to the running total.
  • Subtract it from the running total.

By recursively exploring both these choices, you can determine if the target sum can be achieved. This will involve exploring all 2^n combinations, where n is the length of the array.

Code:

2. Memoization (Top-Down DP)

The recursive approach has a lot of overlapping subproblems, hence we can use memoization to store and reuse the results of these subproblems.

Intuition:

By using a hashmap to save previously computed results, we can avoid redundant calculations. The key is to store the index and the current sum as a tuple (or concatenated string) to uniquely identify each state.

Code:

3. Dynamic Programming (Bottom-Up DP)

We can further optimize by using a bottom-up approach to construct a dp array. This transforms the problem of target sum into a subset sum problem using transformation and leads to more efficient computation.

Intuition:

Consider the equation sum(P) - sum(N) = target, where P is the positive subset and N is the negative subset. The transformation gives sum(P) = (target + sum(nums)) / 2. Hence, this reduces to counting how many ways we can pick a subset of nums that adds up to this sum.

This requires target + sum(nums) to be even and non-negative.

Code: