Data Structures & Algorithms Dynamic Programming — 2D
💡
Exercise 135

Target Sum 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Assign + or - to each number in an array to make the sum equal to target. Count the number of ways.

nums = [1, 1, 1, 1, 1], 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 # Answer: 5 ways

Use a hashmap DP: dp[sum] = number of ways to reach that sum. Process each number, updating possible sums.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Count ways to assign +/- to reach target. nums=[1,1,1,1,1], target=3.
Use Counter/dict. Start with {0: 1}. For each num, create new dict: for each (s, count), add to s+num and s-num.
🧪 Test Cases
Input
findTargetSumWays([1,1,1,1,1], 3)
Expected
5
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.