Overview
This looks like a Backtracking problem at first. However, we can use a math trick to convert it into a pure DP subset counting problem.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
You are given an integer array and a target integer. Assign '+' or '-' to each integer so that the sum evaluates to the target. Return the number of different ways to do this.
This looks like a Backtracking problem at first. However, we can use a math trick to convert it into a pure DP subset counting problem.
Let `P` be the sum of positive numbers, and `N` be the sum of negative numbers. We know `P - N = Target` and `P + N = TotalSum`. Solving for `P` gives: `P = (Target + TotalSum) / 2`.
The problem is completely reduced to: "Find the number of subsets whose sum is exactly `P`". This is standard 0/1 Knapsack.
If `Target + TotalSum` is odd, or if `abs(Target) > TotalSum`, it's mathematically impossible to reach the target, so we return `0` immediately.