-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_494.java
64 lines (55 loc) · 1.65 KB
/
_494.java
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
62
63
64
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* LeetCode 494 - Target Sum
* <p>
* Knapsack
*/
public class _494 {
public int findTargetSumWays(int[] nums, int S) {
final int OFFSET = 1001;
int[] f = new int[2 * OFFSET];
f[0 + OFFSET] = 1;
for (int num : nums) {
int[] g = new int[2 * OFFSET];
for (int i = 0; i < g.length; i++) {
if (i + num < g.length) g[i] += f[i + num];
if (i - num >= 0) g[i] += f[i - num];
}
f = g;
}
return -OFFSET <= S && S <= OFFSET ? f[S + OFFSET] : 0;
}
@Test
public void test() {
int[] nums = {1, 1, 1, 1, 1};
int S = 3;
int expected = 5;
int actual = new _494().findTargetSumWays(nums, S);
assertEquals(expected, actual);
}
@Test
public void test1() {
int[] nums = {};
int S = 0;
int expected = 1;
int actual = new _494().findTargetSumWays(nums, S);
assertEquals(expected, actual);
}
@Test
public void test2() {
int[] nums = {2, 107, 109, 113, 127, 131, 137, 3, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 47, 53};
int S = 2147483647;
int expected = 0;
int actual = new _494().findTargetSumWays(nums, S);
assertEquals(expected, actual);
}
@Test
public void test3() {
int[] nums = {2, 107, 109, 113, 127, 131, 137, 3, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 47, 53};
int S = -2147483648;
int expected = 0;
int actual = new _494().findTargetSumWays(nums, S);
assertEquals(expected, actual);
}
}