-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsetSumProblem.java
More file actions
42 lines (33 loc) · 1.08 KB
/
SubsetSumProblem.java
File metadata and controls
42 lines (33 loc) · 1.08 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
public class Solution {
public int solve(int[] A, int B) {
int n = A.length;
boolean[][] dp = new boolean[n][B + 1];
boolean[][] visited = new boolean[n][B + 1];
return helperTopDownDp(A, n, 0, B, dp, visited) ? 1 : 0;
}
boolean helperTopDownDp(int[] A, int n, int index, int sum, boolean[][] dp, boolean[][] visited)
{ //System.out.println(index + " " + sum);
if(sum == 0)
{
//System.out.println("Found");
return true;
}
if(index == n || sum <= 0)
{
return false;
}
//System.out.println(A[index] + " " + sum);
if(!visited[index][sum])
{
visited[index][sum] = true;
if(A[index] <= sum)
if(helperTopDownDp(A, n, index + 1, sum - A[index], dp, visited))
{
dp[index][sum] = true;
return true;
}
}
dp[index][sum] = dp[index][sum] || helperTopDownDp(A, n, index + 1, sum, dp, visited);
return dp[index][sum];
}
}