494. Target Sum
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- 2-D Dynamic Programming
- Time
- O(n * sum)
- Space
- O(sum)
Standard Solution (C++)
SummaryCount the number of ways to assign a plus or minus sign to each number so the signed sum equals a given target.
Approach
Key idea: If P is the set assigned plus and N the set assigned minus, then sum(P) - sum(N) = target and sum(P) + sum(N) = total, so sum(P) = (total + target) / 2. The answer is the number of subsets summing to that value.
Steps:
- If (total + target) is negative or odd, there are zero ways.
- Let need = (total + target) / 2 and count subsets summing to 'need' with a counting DP.
- For each number, update counts from high sums down to the number.
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int total = 0;
for (int x : nums) total += x;
long shifted = (long)total + target;
if (shifted < 0 || shifted % 2 != 0) return 0;
int need = (int)(shifted / 2);
vector<int> dp(need + 1, 0);
dp[0] = 1;
for (int num : nums) {
for (int s = need; s >= num; --s) {
dp[s] += dp[s - num];
}
}
return dp[need];
}
}; Time O(n * sum) Space O(sum)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.