Target Sum – Leetcode

Problem

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:

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.

 

Solution

Using subset sum solver.

package com.programtalk.learn.interview.questions;
/**
 * 
 * programtalk.com
 *
 */
public class TargetSumProblem {

	public static void main(String[] args) {
		System.out.println(new TargetSumProblem().findTargetSumWays(new int[] { 1, 1, 1, 1, 1 }, 3));
	}

	public int findTargetSumWays(int[] nums, int s) {
		int sum = 0;
		for (int i = 0; i < nums.length; i++) {
			sum += nums[i];
			nums[i] += nums[i];
		}
		if (sum < s) {
			return 0;
		}
		return subsetSum(nums, s + sum);
	}

	public int subsetSum(int[] numbers, int s) {
		int n = numbers.length, nw[][] = new int[s + 1][n + 1];
		nw[0][0] = 1;
		for (int i = 0; i <= s; i++) {
			for (int j = 1; j <= n; j++) {
				nw[i][j] = nw[i][j - 1];
				if (i - numbers[j - 1] >= 0) {
					nw[i][j] += nw[i - numbers[j - 1]][j - 1];
				}
			}
		}
		return nw[s][n];
	}
}


Like this post? Don’t forget to share it!