Java

import java.util.stream.IntStream;

/**

 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.

 */
public class Target_Sum {

    public static void main(String[] args) {
        Target_Sum out = new Target_Sum();
        Solution s = out.new Solution();

        System.out.println(s.findTargetSumWays(new int[]{1,1,1,1,1}, 3));
    }

    class Solution2 {

        int res = 0;
        public int findTargetSumWays(int[] nums, int S) {
            dfs(nums, S, 0);
            return res;
        }

        void dfs(int[] nums, int S, int cur){
            if(cur == nums.length){
                if(S == 0)
                    res+=1;
            }else{
                dfs(nums, S-nums[cur], cur+1);
                dfs(nums, S+nums[cur], cur+1);
            }
        }

    }

    class Solution {

        int count = 0;

        public int findTargetSumWays(int[] nums, int target) {
            dfs(nums, 0, target);

            return count;
        }

        private void dfs(int[] nums, int i, int target) {
            int sum = IntStream.range(0, i+1).map(p -> nums[p]).sum(); // possible overflow

            if (i == nums.length) {
                if (sum == target) {
                    count++;
                }
                return;
            }

            dfs(nums, i+1, target);

            nums[i] *= (-1); // also overflow
            dfs(nums, i+1, target);
            nums[i] *= (-1);

        }
    }
}

Java

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

All Problems

All Solutions