Target Sum

Leetcode 494 - Target Sum

First we have to visualise the problem For this array we apply either a subtract operation or addition operation on each value sequentially to reach some target number.

Therefore the value of the sum after the first index is or . If we, simulate both operation and map out all the possible values for each index then we get the following.

For index 4 one of the possible target values is 5. The value for index 4, , means that to reach 5 we have to add or subtract . Therefore we would need to have a value of 6 or 4 as .

The possible values we can have at index 3 only contain . If we repeat this process then we find out there is only one way to get by index 3.

Defining the Subproblem

We need to find the target sum, therefore we can describe our subproblem as: β€œThe number of expressions which evaluate to a target at index ”

Therefore for array :

I realised that for each index that the value of would be different. It is possible to get and at index 0 but not possible to get those values at index 1.
If we consider the target 0 at index 1 there are two ways to get there. We can either subtract 1 from 1 to get 0 or add 1 to -1 to get 0. Therefore the number of expressions would be the number of ways to evaluate 1 plus the number of ways to evaluate -1.

BFS + Memoization

https://leetcode.com/problems/target-sum/description/ Write up BFS + MEMO SOLUTION