Imagine you have a list of numbers and want to assign '+' or '-' signs to each so that the total equals a target sum. How many ways can you do this?
Given an array of integers nums and an integer target, return the number of different expressions that can be built by adding '+' or '-' before each integer such that the resulting expression evaluates to target.
Input: nums (list of integers), target (integer)
Output: integer representing the count of valid expressions.
1 ≤ nums.length ≤ 200 ≤ nums[i] ≤ 10000 ≤ sum(nums[i]) ≤ 1000-1000 ≤ target ≤ 1000
Edge cases: nums = [0,0,0,0,0], target = 0 → 32 (all combinations of + and - count)nums = [1000], target = 1000 → 1 (only +1000 works)nums = [1], target = 2 → 0 (no way to reach 2)
def findTargetSumWays(nums: list[int], target: int) -> int:public int findTargetSumWays(int[] nums, int target)int findTargetSumWays(vector<int>& nums, int target)function findTargetSumWays(nums, target)
def findTargetSumWays(nums, target):
# Write your solution here
pass
class Solution {
public int findTargetSumWays(int[] nums, int target) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int findTargetSumWays(vector<int>& nums, int target) {
// Write your solution here
return 0;
}
function findTargetSumWays(nums, target) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: 0Base case returns 0 instead of 1 when index == len(nums) and current sum == target.✅ Change base case to return 1 if current sum equals target at recursion end.
Wrong: 1Ignoring sign assignments for zeros, counting only one way instead of 2^count_of_zeros.✅ Branch on both + and - for zeros as well to count all combinations.
Wrong: Nonzero for impossible targetIncorrect base case or pruning allowing invalid sums to count.✅ Return 0 when sums do not match target at recursion end.
Wrong: Wrong count due to greedy approachGreedy sign assignment misses multiple valid ways.✅ Use DP or recursion to enumerate all sign assignments.
Wrong: TLEUsing brute force recursion without memoization for large n.✅ Implement memoization or bottom-up DP to reduce complexity to O(n*sum).