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:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.

1.递归

public class Solution {
    int count = 0;
    public int findTargetSumWays(int[] nums, int S) {
        calculate(nums, 0, 0, S);
        return count;
    }
    public void calculate(int[] nums, int i, int sum, int S) {
        if (i == nums.length) {
            if (sum == S)
                count++;
        } else {
            calculate(nums, i + 1, sum + nums[i], S);
            calculate(nums, i + 1, sum - nums[i], S);
        }
    }
}

时间复杂度:O(2^n)

2.DP

题目中明确指出所有数字之合不大于1000,因此可以用一个长度为2001的数组(-1000~1000)来保存当前的加减结果,即:index为值,value为次数,最后返回值为S的次数即可:

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        if (S > 1000 || S < -1000) return 0;
        Integer tmp[] = new Integer[2001];
        tmp[nums[0] + 1000] = 1;
        tmp[1000 - nums[0]] = nums[0] == 0 ? 2 : 1;
        for (int i = 1; i < nums.length; i++) {
            Integer newTmp[] = new Integer[2001];
            for (int j = 0; j < 2001; j++) {
                if (tmp[j] != null) {
                    newTmp[j + nums[i]] = newTmp[j + nums[i]] == null ? tmp[j] : newTmp[j + nums[i]] + tmp[j];
                    newTmp[j - nums[i]] = newTmp[j - nums[i]] == null ? tmp[j] : newTmp[j - nums[i]] + tmp[j];
                }
            }
            tmp = newTmp;
        }
        return tmp[S + 1000] == null ? 0 : tmp[S + 1000];
    }
}

时间复杂度:O(n*l)
空间复杂度: O(n)