Target Sum (Leetcode 494) - Coding Interview Question
You are given an integer array nums
and an integer target
.
You want to build an expression out of nums by adding one of the symbols '+'
and
'-'
before each integer in nums and then concatenate all the integers.
- For example, if
nums = [2, 1]
, you can add a'+'
before2
and a'-'
before1
and concatenate them to build the expression"+2-1"
.
Return the number of different expressions that you can build, which evaluates to
target
.
Example 1:
Input: nums = [1,1,1,1,1], target = 3 Output: 5 Explanation: There are 5 ways to assign symbols to make the sum of nums be target 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 +1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input: nums = [1], target = 1 Output: 1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
Solution:
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Intuition: This is a 0/1 knapsack dp. This is equivalent to given an array of numbers, count the
* number of subsets whose sum of elements is = (arraySum + target) / 2. Here all the elemenets
* with + sign can be considered as grouped into subset1 and all elements of - sign are grouped into subset2.
* One thing to note is that if the arraySum + target is odd it means we cannot divide the array into two halfs
* with that sum.
* <p>
* Time Complexity: O(N ^ 2)
* Space Complexity: O(N ^ 2)
**/
class Solution {
public int findTargetSumWays(int[] a, int target) {
int sum = 0;
int zeros = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 0) {
zeros++;
} else {
sum += a[i];
}
}
int[] w = new int[a.length - zeros];
int k = 0;
for (int i : a) {
if (i != 0) {
w[k++] = i;
}
}
int c = sum + target;
if (c % 2 == 1) {
return 0;
}
c = c / 2;
int[][] dp = new int[w.length + 1][c + 1];
for (int i = 0; i < dp.length; i++) {
dp[i][0] = 1;
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (w[i - 1] <= j) {
dp[i][j] = dp[i - 1][j - w[i - 1]] + dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
// for(int d[] : dp) {
// System.out.println(Arrays.toString(d));
// }
return dp[w.length][c] * (int) Math.pow(2, zeros);
}
}