Tuesday, June 6, 2017

494. Target Sum

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S. 
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3. 
Output: 5
Explanation: 

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
  1. The length of the given array is positive and will not exceed 20. 
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.



Solution:

Method 1: DFS

This problem is a simplified version of Expression Add Operators

We only need to consider + and -.

We go through each number and try + or -. When we reach the end of the input, we check if the sum equals to the target.

If so, we increment the result.

The time complexity is O(2n), since we have two choices at each position.



Code:


public class Solution {
    private int result = 0;
    public int findTargetSumWays(int[] nums, int S) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        helper(nums, S, 0, 0);
        return result;
    }
    public void helper(int[] nums, int target, int sum, int pos) {
        if (pos == nums.length) {
            if (sum == target) {
                result++;
            }
            return;
        }
        helper(nums, target, sum + nums[pos], pos + 1);
        helper(nums, target, sum - nums[pos], pos + 1);
    }
}



Method 2: Dynamic Programming

The idea is to split the numbers into two partitions: nums with '+' and nums with '-'.

We want find such partition that

sum(P) - sum(N) == target

sum(P) - sum(N) + sum(All) == target + sum(All)

sum(P) - sum(N) + sum(P) + sum(N) == target + sum(All)

sum(P) == (target + sum(All)) / 2

We know sum(P) is still integer. So if target + sum(All) is odd number, there is no such partition.

Otherwise, the problem becomes Partition Equal Subset Sum.

The time complexity is O(n2) and the space complexity is O(n).



Code:


public class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum < S || (S + sum) % 2 != 0) {
            return 0;
        }
        return findWays(nums, (S + sum) / 2);
    }
    
    public int findWays(int[] nums, int target) {
        int[] ways = new int[target + 1];
        ways[0] = 1;
        for (int num : nums) {
            for (int i = target; i >= num; i--) {
                ways[i] += ways[i - num];
            }
        }
        return ways[target];
    }
}