Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Dynamic Programming.
- *
- * As per the question, Sum(P) + Sum(N) = Sum(nums). Also, Sum(P) - Sum(N) =
- * target. Thus if we add these two equations, we will get:
- *
- * 2 * Sum(P) = target + Sum(nums)
- *
- * OR
- *
- * Sum(P) = (target + Sum(nums)) / 2
- *
- * One we have the target sum of positive numbers, the probelm reduces to
- * 416-Partition Equal Subset Sum question. Refer to this question's solution
- * for explaination on how to find the subset.
- * (https://leetcode.com/problems/partition-equal-subset-sum)
- *
- * Only change here, we have to return the number of ways we can create these
- * subsets. Thus DP transformation will modify to:
- *
- * DP[i][s] = DP[i-1][s] + DP[i-1][s - nums[i]]
- *
- * This problem has the same explaination for finding the subset
- */
- class Solution {
- public int findTargetSumWays(int[] nums, int S) {
- if (nums == null || (nums.length == 0 && S > 0)) {
- return 0;
- }
- if (nums.length == 0 && S == 0) {
- return 1;
- }
- int sum = 0;
- for (int num : nums) {
- sum += num;
- }
- if (S > sum || (S + sum) % 2 != 0) {
- return 0;
- }
- int target = (S + sum) / 2;
- int[] dp = new int[target + 1];
- dp[0] = 1;
- for (int num : nums) {
- for (int s = target; s >= num; s--) {
- dp[s] += dp[s - num];
- }
- }
- return dp[target];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement