LeetCode 494. Target Sum

Question

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
2
3
4
5
6
7
8
9
10
11
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

When I see the input size, I am thinking n^3 solution should work. So, I try DFS method to explore different combinations and then after consideration, we can cache results that will used so many times. For this question, I’d like to use rest of sum and index to mark the unqiue status and cache. But at this time, I didn’t use 2-D array because sum may exists as negative number. So, I’d like to use HashMap to store.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// time:O(2^n) space:O(n)
// search, backtracking
public int findTargetSumWays(int[] nums, int S) {
if (nums == null || nums.length == 0) return 0;
int n = nums.length;
return dfs(nums, 0, S, 0, 0);
}

public int dfs(int[] nums, int index, int target, int val, int prev) {
if (index == nums.length) {
if (val == target) return 1;
return 0;
}
int res = 0;
res += dfs(nums, index + 1, target, val + nums[index], nums[index]);
res += dfs(nums, index + 1, target, val - nums[index], -nums[index]);
return res;
}


// dfs + memo
public int findTargetSumWays2(int[] nums, int S) {
if (nums == null || nums.length == 0) return 0;
HashMap<String, Integer> map = new HashMap<>();
return dfs(nums, 0, S, map);
}

// time:O(sum * n) space:O(n)
public int dfs(int[] nums, int index, int target, HashMap<String, Integer> map) {
String key = index + "-" + target;
if (index == nums.length) {
if (target == 0) return 1;
return 0;
}
if (map.get(key) != null) return map.get(key);

int res = 0;
res += dfs(nums, index + 1, target - nums[index], map);
res += dfs(nums, index + 1, target + nums[index], map);
map.put(key, res);
return res;
}