1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public int findTargetSumWays(int[] nums, int target) { int n = nums.length; int sum = 0; for(int num : nums){ sum += num; }
if((sum - target)<0 || (sum - target)%2 != 0){ return 0; }
int neg = (sum - target)/2; int[][] dp = new int[n+1][neg+1]; dp[0][0] = 1; for(int i = 1; i <= n; i++){ for(int j = 0; j <= neg; j++){ dp[i][j] = dp[i-1][j]; if(j >= nums[i-1]){ dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]]; } } } return dp[n][neg]; } }
|