1
+ package DynamicProgramming ;
2
+
3
+ public class SubsetSum {
4
+
5
+ /**
6
+ * Driver Code
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
+ }
15
+
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 ];
26
+
27
+ isSum [n + 1 ][0 ] = true ;
28
+ for (int i = 1 ; i <= sum ; i ++) {
29
+ isSum [n + 1 ][i ] = false ;
30
+ }
31
+
32
+ for (int i = n ; i > 0 ; i --) {
33
+ isSum [i ][0 ] = true ;
34
+ for (int j = 1 ; j <= arr [i - 1 ] - 1 ; j ++) {
35
+ if (j <= sum ) {
36
+ isSum [i ][j ] = isSum [i + 1 ][j ];
37
+ }
38
+ }
39
+ for (int j = arr [i - 1 ]; j <= sum ; j ++) {
40
+ isSum [i ][j ] = (isSum [i + 1 ][j ] || isSum [i + 1 ][j - arr [i - 1 ]]);
41
+ }
42
+ }
43
+
44
+ return isSum [1 ][sum ];
45
+ }
46
+ }
0 commit comments