494 Target Sum

494. Target Sum

1. 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:
1
Input: nums is [1, 1, 1, 1, 1], S is 3.
2
3
Output: 5
4
5
Explanation:
6
7
-1+1+1+1+1 = 3
8
+1-1+1+1+1 = 3
9
+1+1-1+1+1 = 3
10
+1+1+1-1+1 = 3
11
+1+1+1+1-1 = 3
12
13
There are 5 ways to assign symbols to make the sum of nums be target 3.
Copied!
Note:
  1. 1.
    The length of the given array is positive and will not exceed 20.
  2. 2.
    The sum of elements in the given array will not exceed 1000.
  3. 3.
    Your output answer is guaranteed to be fitted in a 32-bit integer.

2. Implementation

(1) DFS
1
public class Solution {
2
public int findTargetSumWays(int[] nums, int S) {
3
int[] res = new int[1];
4
findTargetSum(0, 0, S, nums, res);
5
return res[0];
6
}
7
8
public void findTargetSum(int index, int curSum, int target, int[] nums, int[] res) {
9
if (index == nums.length) {
10
if (curSum == target) {
11
++res[0];
12
}
13
return;
14
}
15
16
findTargetSum(index + 1, curSum + nums[index], target, nums, res);
17
findTargetSum(index + 1, curSum - nums[index], target, nums, res);
18
}
19
}
Copied!
(2) 2D DP
1
class Solution {
2
public int findTargetSumWays(int[] nums, int S) {
3
int sum = 0;
4
5
for (int num : nums) {
6
sum += num;
7
}
8
9
if (sum < S || (sum + S) % 2 != 0) {
10
return 0;
11
}
12
13
return getWaysToSubsetSum(nums, (sum + S)/2);
14
}
15
16
public int getWaysToSubsetSum(int[] nums, int target) {
17
int n = nums.length;
18
int[][] dp = new int[n + 1][target + 1];
19
dp[0][0] = 1;
20
21
for (int i = 1; i <= n; i++) {
22
// Target要从0开始
23
for (int j = 0; j <= target; j++) {
24
if (nums[i - 1] <= j) {
25
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - nums[i - 1]];
26
}
27
else {
28
dp[i][j] = dp[i - 1][j];
29
}
30
}
31
}
32
return dp[n][target];
33
}
34
}
Copied!
(3) 1D DP
1
class Solution {
2
public int findTargetSumWays(int[] nums, int S) {
3
int sum = 0;
4
5
for (int num : nums) {
6
sum += num;
7
}
8
9
if (sum < S || (sum + S) % 2 != 0) {
10
return 0;
11
}
12
13
return getWaysToSubsetSum(nums, (sum + S)/2);
14
}
15
16
public int getWaysToSubsetSum(int[] nums, int target) {
17
int n = nums.length;
18
int[] dp = new int[target + 1];
19
dp[0] = 1;
20
21
// 0-1背包模板
22
for (int i = 0; i < n; i++) {
23
for (int j = target; j >= nums[i]; j--) {
24
dp[j] += dp[j - nums[i]];
25
}
26
}
27
return dp[target];
28
}
29
}
Copied!

3. Time & Space Complexity

DFS: 时间复杂度O(2^n), 空间复杂度O(2^n)
2D DP: 时间复杂度O(n * target), 空间复杂度O(n * target)
1D DP: 时间复杂度O(n * target), 空间复杂度O(target)