-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path494.java
More file actions
45 lines (40 loc) · 1.44 KB
/
494.java
File metadata and controls
45 lines (40 loc) · 1.44 KB
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
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public int findTargetSumWays(int[] nums, int S) {
if(nums.length == 0) return 0;
int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
}
if(sum < S) return 0; // if I add them like crazy, I still cannot get S
if( ( sum - S ) % 2 != 0) return 0;
int target = (sum - S) / 2;
int[] cache = new int[target+1];
cache[0] = 1;
for(int i = 0; i < nums.length; i++) {
int curNum = nums[i];
for(int j = cache.length-1; j>=curNum; j--) {
cache[j] += cache[j-curNum];
}
}
return cache[cache.length-1];
}
}
__________________________________________________________________________________________________
sample 34532 kb submission
class Solution {
private int[] nums;
public int findTargetSumWays(int[] nums, int S) {
int max = IntStream.of(nums).map(Math::abs).sum();
if (S > max || S < -max) return 0;
this.nums = nums;
return findTargetSumWays(S, 0);
}
private int findTargetSumWays(int S, int i) {
if (i == nums.length) return S == 0 ? 1 : 0;
return findTargetSumWays(S + nums[i], i + 1) +
findTargetSumWays(S - nums[i], i + 1);
}
}
__________________________________________________________________________________________________