forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsetSumPossibility.java
More file actions
45 lines (40 loc) · 1.41 KB
/
SubsetSumPossibility.java
File metadata and controls
45 lines (40 loc) · 1.41 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
import java.util.Arrays;
public class Subset {
/**
subsetSumPossible(@param set, @param sum) is a function to check if it is possible
to obtain the @param sum from the subset of integer array @param set.
Returns true if it's possible to obtain the @param sum from the subset or else returns false.
*/
private static boolean subsetSumPossible(int[] set, int sum){
int[][] table = new int[set.length+1][sum+1];
for (int i=1; i<=set.length; i++){
for(int s=0; s<=sum; s++){
if (s==0){
table[i][s] = 1;
}
else if(s < set[i-1]){
table[i][s] = table[i-1][s];
}
else if(s == set[i-1]){
table[i][s] = 1;
}
else if(table[i-1][s] == 1){
table[i][s] = 1;
}else{
table[i][s] = table[i-1][s - set[i-1]];
}
}
}
System.out.println(Arrays.deepToString(table));
return table[set.length][sum] == 1;
}
public static void main(String[] args) {
int[] set = {2, 3}; //{3, 34, 4, 12, 5, 2};
int sum = 14; //14;
if (subsetSumPossible(set, sum)){
System.out.println("Subset is possibile");
}else {
System.out.println("Subset is not possibile");
}
}
}l̥