@@ -6,24 +6,36 @@ public static void main(String[] args) {
6
6
int [] arr = {7 , 3 , 2 , 5 , 8 };
7
7
int Key = 14 ;
8
8
9
- if (subsetSum (arr , arr .length - 1 , Key )) {
9
+ if (subsetSum (arr , arr .length , Key )) {
10
10
System .out .print ("Yes, that sum exists" );
11
11
} else {
12
12
System .out .print ("Nope, that number does not exist" );
13
13
}
14
14
}
15
15
16
- public static boolean subsetSum (int [] arr , int num , int Key ) {
17
- if (Key == 0 ) {
18
- return true ;
19
- }
20
- if (num < 0 || Key < 0 ) {
21
- return false ;
16
+ static boolean subsetSum (int [] arr , int n , int Key ) {
17
+ boolean [] prev = new boolean [Key + 1 ];
18
+
19
+ prev [0 ] = true ;
20
+
21
+ if (arr [0 ] <= Key ) {
22
+ prev [arr [0 ]] = true ;
22
23
}
23
24
24
- boolean include = subsetSum (arr , num - 1 , Key - arr [num ]);
25
- boolean exclude = subsetSum (arr , num - 1 , Key );
25
+ for (int ind = 1 ; ind < n ; ind ++) {
26
+ boolean [] cur = new boolean [Key + 1 ];
27
+ cur [0 ] = true ;
28
+ for (int target = 1 ; target <= Key ; target ++) {
29
+ boolean notTaken = prev [target ];
30
+ boolean taken = false ;
31
+ if (arr [ind ] <= target ) {
32
+ taken = prev [target - arr [ind ]];
33
+ }
34
+ cur [target ] = notTaken || taken ;
35
+ }
36
+ prev = cur ;
37
+ }
26
38
27
- return include || exclude ;
39
+ return prev [ Key ] ;
28
40
}
29
41
}
0 commit comments