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.
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.
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 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
+1 + 1 + 1 + 1 - 1 = 3
Input: nums = [1], target = 1
Output: 1
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums[i]) <= 1000-1000 <= target <= 1000The first approach uses recursion to explore all possible ways to add or subtract numbers from the array to achieve the target sum.
For each number in the array, you have two choices:
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.
O(2^n), where n is the number of elements in the array. This is because we are exploring both add and subtract options for each number.O(n), due to the recursive stack space.The recursive approach has a lot of overlapping subproblems, hence we can use memoization to store and reuse the results of these subproblems.
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.
O(n * s), where n is the length of the array and s is the sum of the array. The memoization reduces the number of recursive calls.O(n * s), for the memoization hashmap plus stack space.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.
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.
O(n * s), where n is the length of nums and s is the target sum transformed as above.O(s), where s is the target sum. We use an array proportional to the target sum.