File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Dynamic Programming/2D/Subsequences Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ import java .io .*;
3+ public class SubsetSumToK {
4+ public static boolean subsetSumToK (int n , int k , int arr []){
5+ boolean [][] dp = new boolean [n ][k +1 ];
6+
7+ for (int i = 0 ; i <n ; i ++){
8+ dp [i ][0 ] = true ; // can form sum 0 by not picking the 'i'th element
9+ }
10+
11+ for (int j = 0 ; j <k +1 ; j ++){
12+ if (j == arr [0 ]){
13+ dp [0 ][j ] = true ;
14+ }
15+ }
16+
17+ for (int i = 1 ; i <n ; i ++){
18+ for (int j = 1 ; j <k +1 ; j ++){
19+ if (arr [i ]<=k ){
20+ dp [i ][arr [i ]] = true ;
21+ }
22+ if (j >=arr [i ]){
23+ dp [i ][j ] = dp [i -1 ][j ] || dp [i -1 ][j -arr [i ]]; // not pick or pick. pick -> check remaining sum
24+ }
25+ else {
26+ dp [i ][j ] = dp [i -1 ][j ];
27+ }
28+
29+ }
30+ }
31+
32+ return dp [n -1 ][k ];
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments