2
2
3
3
public class SubsetSum {
4
4
5
- /*
6
- This algorithm will determine if a set of integers contains
7
- a subset that sum to a given integer. The algorithm will
8
- return true if such a subset exists and false otherwise.
9
- This is a dynamic programming implementation.
5
+ /**
6
+ * Driver Code
10
7
*/
8
+ public static void main (String [] args ) {
9
+ int [] arr = new int []{50 , 4 , 10 , 15 , 34 };
10
+ assert subsetSum (arr , 64 ); /* 4 + 10 + 15 + 34 = 64 */
11
+ assert subsetSum (arr , 99 ); /* 50 + 15 + 34 = 99 */
12
+ assert !subsetSum (arr , 5 );
13
+ assert !subsetSum (arr , 66 );
14
+ }
11
15
12
- private static boolean subsetSum (int arr [], int n , int sum ){
13
- boolean isSum [][] = new boolean [n + 2 ][sum + 1 ];
16
+ /**
17
+ * Test if a set of integers contains a subset that sum to a given integer.
18
+ *
19
+ * @param arr the array contains integers.
20
+ * @param sum target sum of subset.
21
+ * @return {@code true} if subset exists, otherwise {@code false}.
22
+ */
23
+ private static boolean subsetSum (int [] arr , int sum ) {
24
+ int n = arr .length ;
25
+ boolean [][] isSum = new boolean [n + 2 ][sum + 1 ];
14
26
15
27
isSum [n + 1 ][0 ] = true ;
16
28
for (int i = 1 ; i <= sum ; i ++) {
@@ -31,27 +43,4 @@ private static boolean subsetSum(int arr[], int n, int sum){
31
43
32
44
return isSum [1 ][sum ];
33
45
}
34
-
35
- /*
36
- This is a driver method to run the algorithm with four
37
- test values: the first two should evaluate true, and the
38
- last two should evaluate false.
39
- */
40
- public static void main (String args []) {
41
- int arr [] = new int []{50 , 4 , 10 , 15 , 34 };
42
- int n = arr .length ;
43
- // 4 + 10 + 15 + 34 = 64
44
- int sum1 = 64 ;
45
- // 50 + 15 + 34 = 99
46
- int sum2 = 99 ;
47
- // No subset of the given array will give a sum
48
- // of 5 or 66
49
- int sum3 = 5 ;
50
- int sum4 = 66 ;
51
-
52
- System .out .println (subsetSum (arr , n , sum1 ));
53
- System .out .println (subsetSum (arr , n , sum2 ));
54
- System .out .println (subsetSum (arr , n , sum3 ));
55
- System .out .println (subsetSum (arr , n , sum4 ));
56
- }
57
46
}
0 commit comments