Advertisement
1988coder

494. Target Sum

Jan 3rd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. /**
  2.  * Dynamic Programming.
  3.  *
  4.  * As per the question, Sum(P) + Sum(N) = Sum(nums). Also, Sum(P) - Sum(N) =
  5.  * target. Thus if we add these two equations, we will get:
  6.  *
  7.  * 2 * Sum(P) = target + Sum(nums)
  8.  *
  9.  * OR
  10.  *
  11.  * Sum(P) = (target + Sum(nums)) / 2
  12.  *
  13.  * One we have the target sum of positive numbers, the probelm reduces to
  14.  * 416-Partition Equal Subset Sum question. Refer to this question's solution
  15.  * for explaination on how to find the subset.
  16.  * (https://leetcode.com/problems/partition-equal-subset-sum)
  17.  *
  18.  * Only change here, we have to return the number of ways we can create these
  19.  * subsets. Thus DP transformation will modify to:
  20.  *
  21.  * DP[i][s] = DP[i-1][s] + DP[i-1][s - nums[i]]
  22.  *
  23.  * This problem has the same explaination for finding the subset
  24.  */
  25. class Solution {
  26.     public int findTargetSumWays(int[] nums, int S) {
  27.         if (nums == null || (nums.length == 0 && S > 0)) {
  28.             return 0;
  29.         }
  30.         if (nums.length == 0 && S == 0) {
  31.             return 1;
  32.         }
  33.  
  34.         int sum = 0;
  35.         for (int num : nums) {
  36.             sum += num;
  37.         }
  38.         if (S > sum || (S + sum) % 2 != 0) {
  39.             return 0;
  40.         }
  41.         int target = (S + sum) / 2;
  42.  
  43.         int[] dp = new int[target + 1];
  44.         dp[0] = 1;
  45.         for (int num : nums) {
  46.             for (int s = target; s >= num; s--) {
  47.                 dp[s] += dp[s - num];
  48.             }
  49.         }
  50.  
  51.         return dp[target];
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement