-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTargetSum.java
73 lines (57 loc) · 2.15 KB
/
TargetSum.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
65
66
67
68
69
70
71
72
73
class Solution {
int totalWays = 0;
public int findTargetSumWays(int[] nums, int target) {
int n = nums.length;
// recursion
// findWaysRec(nums, 0, 0, target);
// return totalWays;
// memoization
int totalSum = 0;
for(int num : nums){
totalSum += num;
}
// For sum range [-8,+8] => new range => [0, 16] indices of the `dp` array
int[][] dp = new int[n][2 * totalSum + 1];
for(int[] row : dp){
Arrays.fill(row, Integer.MIN_VALUE);
}
return findWaysMemo(nums, 0, 0, target, dp, totalSum);
}
// memoization => TC: O(n*totalSum)
public int findWaysMemo(int[] nums, int n, int currentSum, int target, int[][] dp, int totalSum){
if(n == nums.length){
if(currentSum == target){
return 1; // found 1 way to reach this target
} else{
return 0; // did not find a way
}
}
// handling negative indices
// if we already calculated this subproblem before, just return its value
if(dp[n][currentSum + totalSum] != Integer.MIN_VALUE){
return dp[n][currentSum + totalSum];
}
// take positive sign
int positive = findWaysMemo(nums, n + 1, currentSum + nums[n], target, dp, totalSum);
// take negative sign
int negative = findWaysMemo(nums, n + 1, currentSum - nums[n], target, dp, totalSum);
// store total ways from both choices
dp[n][currentSum + totalSum] = positive + negative;
return dp[n][currentSum + totalSum];
}
// recursion
// TC: O(2^n) very bad
public void findWaysRec(int[] nums, int currentIdx, int currentSum, int target){
if(currentIdx == nums.length){
if(currentSum == target){
totalWays += 1;
}
}
else{
// take negative
findWaysRec(nums, currentIdx + 1, currentSum - nums[currentIdx], target);
// take positive
findWaysRec(nums, currentIdx + 1, currentSum + nums[currentIdx], target);
}
}
}