Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 494 Target Sum - Walkthrough

Signs to subsets

Trace Target Sum on nums=[1,1,1,1,1]nums = [1, 1, 1, 1, 1] with target S=3S = 3. Sum is 55. We need (5+3)/2=4(5 + 3) / 2 = 4 as the positive subset sum. Find subsets summing to 44. Count dp[s]dp[s] = number of ways to make sum ss. After processing all five 11s: dp[0]=1dp[0]=1, dp[1]=5dp[1]=5, dp[2]=10dp[2]=10, dp[3]=10dp[3]=10, dp[4]=5dp[4]=5, dp[5]=1dp[5]=1.

Answer: dp[4]=5dp[4] = 5 ways. These correspond to choosing 44 ones as positive and 11 as negative: +1+1+1+11=3+1+1+1+1-1 = 3.