Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 494 Target Sum - Converting Signs to Subsets

The math

Let PP = sum of numbers with + sign, NN = sum of numbers with - sign. You know: PN=targetP - N = target and P+N=totalP + N = total. Add these equations: 2P=target+total2P = target + total, so P=(target+total)/2P = (target + total) / 2. If this isn't an integer, return 0.

Now the problem becomes: count subsets that sum to PP. That's subset sum with counting instead of boolean. The transformation is complete. You're selecting which numbers get the + sign.