14.Target Sum

You are given an integer array nums and an integer target.

You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.

  • For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".

Return the number of different expressions that you can build, which evaluates to target.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. 
Output: 5
Explanation: 

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.

Solution: (Recursion)

Trying both + and - for all values

Time Complexity: O(2^n)

Solution: (Recursion + Memo)

Solution: (Dynamic Programming)

Similar to check if there is a subset with given sum Here we have to count the no of subset with target sum We can assume two subset S1 - S2 = target S1 + S2 = total array sum We can use this two equation to count the no of ways we can create a target sum

Edge Case:- Count all zeros as it can be added to both the subsets

Time Complexity: O(n * m)

Last updated

Was this helpful?