Target Sum

LeetCode Q 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.

Solution :

Solution 1 : DFS / backtracking

Time Complexity: O(2^n)

Code:

private int res;
public int findTargetSumWays(int[] nums, int S) {
  if (nums == null || nums.length == 0) return 0;
  backtrack(nums, S, 0, 0);
  return res;
}

private void backtrack(int[] nums, int S, int index, int currSum) {
  if (index == nums.length) {
    if (currSum == S) res++;
    return;
  }

  //explore
  backtrack(nums, S, index + 1, currSum + nums[index]);
  backtrack(nums, S, index + 1, currSum - nums[index]);

  return;
}

Solution 2 : DP

dp[i][j] refers to the number of assignments which can lead to a sum of j upto the ith index.

State Transfer Function
dp[i][sum+nums[i]] = dp[i][sum+nums[i]]+dp[i-1][sum] dp[i][sum-nums[i]] = dp[i][sum-nums[i]]+dp[i-1][sum]

Note: we add an offset sum to the second index to avoid negative index value.

Time Complexity: O(kn)
Time Complexity: O(kn)

Code:

public int findTargetSumWays(int[] nums, int S) {
  if (nums == null || nums.length == 0) return 0;

  int sum = 0;
  for (int num: nums) sum += num;

  int[][] dp = new int[nums.length][2 * sum + 1];

  dp[0][sum + nums[i]] = 1;
  dp[0][sum - nums[i]] += 1; // = is not correct!

  for (int i = 1; i < nums.length; i++) {
    for (int s = 0; s < 2 * sum + 1; s++) {
      if (dp[i - 1][s] != 0) {
        int n = nums[i];
        dp[i][s + n] += dp[i - 1][s];
        dp[i][s - n] += dp[i - 1][s];
      }
    }
  }

  return dp[nums.length - 1][sum + S];
}

   Reprint policy


《Target Sum》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC