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.
nums always integers?
nums contain negative numbers?
nums contains only non-negative numbers.nums?
20.target?
target can be up to 1000.We need to determine how many ways we can use + and - operators in front of the numbers in the nums array such that the resultant expression evaluates to target. The strategy I’ll use to solve this problem is Depth-First Search (DFS) in combination with memoization to avoid recomputation of results.
def findTargetSumWays(nums, target):
memo = {}
def dfs(i, total):
if i == len(nums):
return 1 if total == target else 0
if (i, total) in memo:
return memo[(i, total)]
# Calculate result by adding and subtracting the current number
add = dfs(i + 1, total + nums[i])
subtract = dfs(i + 1, total - nums[i])
memo[(i, total)] = add + subtract
return memo[(i, total)]
return dfs(0, 0)
O(n * s) where n is the length of nums and s is the sum of elements in nums.total, leading to at most n * 2s subproblems.O(n * s) for the memo dictionary and the call stack in worst case scenario.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?