-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtSubSetSum.java
More file actions
60 lines (49 loc) · 1.48 KB
/
Copy pathAtSubSetSum.java
File metadata and controls
60 lines (49 loc) · 1.48 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class AtSubSetSum {
public static void printTable(boolean subset[][], int x, int y)
{
for (int i = 0 ; i < x ; i++)
{
for (int j = 0 ; j < y ; j++)
System.out.print((subset[i][j] == true ? 'T': 'F') + " ");
System.out.println();
}
}
public static boolean isSubSetSum(int set[], int n , int sum)
{
boolean subset[][] = new boolean[n+1][sum+1];
for (int i = 0 ; i < (n+1) ; i++)
subset[i][0] = true;
for (int i = 1 ; i < (sum+1) ; i++)
subset[1][i] = false;
for (int i = 1; i < (n+1); i++)
{
for (int j = 1; j < (sum+1) ; j++)
{
subset[i][j] = subset[i-1][j];
if (j >= set[i-1])
subset[i][j] = subset[i - 1][j-set[i-1]] ||
subset[i][j];
}
}
printTable(subset, n+1, sum+1);
// Lets print out the numbers
int i = n;
while (i >= 1)
{
if (subset[i][sum] != subset[i-1][sum])
{
System.out.print(set[i-1] + " ");
sum = sum - set[i-1];
}
i--;
}
return subset[n][sum];
}
public static void main(String args[])
{
int sum = 14;
int arr[] = {6, 5, 8, 1};
boolean yes = isSubSetSum(arr, arr.length, sum);
System.out.println("Possible ? " + yes);
}
}