494. Target Sum
Problem
Put + or - in front of every number of nums and concatenate them into an expression. Count the expressions that evaluate to target.
Example: nums = [1,1,1,1,1], target = 3 → 5
Constraints: n ≤ 20; sum of nums ≤ 1000.
Let P = numbers with +. Then P − (total − P) = target ⇒ P = (total + target) / 2. Count subsets summing to P (0/1 knapsack, iterate downward).
Complexity: O(n · P).
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
total = sum(nums)
if abs(target) > total or (total + target) % 2:
return 0
P = (total + target) // 2
dp = [1] + [0] * P
for x in nums:
for s in range(P, x - 1, -1):
dp[s] += dp[s - x]
return dp[P]
assert Solution().findTargetSumWays([1, 1, 1, 1, 1], 3) == 5
assert Solution().findTargetSumWays([1], 1) == 1
assert Solution().findTargetSumWays([0, 0, 1], 1) == 4
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int total = 0;
for (int x : nums) total += x;
if (Math.abs(target) > total || (total + target) % 2 != 0) return 0;
int P = (total + target) / 2;
int[] dp = new int[P + 1];
dp[0] = 1;
for (int x : nums)
for (int s = P; s >= x; s--) dp[s] += dp[s - x];
return dp[P];
}
}
func findTargetSumWays(nums []int, target int) int {
total := 0
for _, x := range nums {
total += x
}
if target > total || -target > total || (total+target)%2 != 0 {
return 0
}
P := (total + target) / 2 // the '+' numbers must sum to P
dp := make([]int, P+1)
dp[0] = 1
for _, x := range nums {
for s := P; s >= x; s-- {
dp[s] += dp[s-x]
}
}
return dp[P]
}