Counting knapsack
Time O(n × P) Space O(P)If total + target is odd or |target| > total, 0. Otherwise ways[0] = 1 and for each x, for s downwards: ways[s] += ways[s − x].
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[] ways = new int[p + 1];
ways[0] = 1;
for (int x : nums)
for (int s = p; s >= x; s--) ways[s] += ways[s - x];
return ways[p];
}
}Verdict: Zeros are handled naturally (each doubles the count).