@@ -122,3 +122,34 @@ public int minPartition(int A[]){
122
122
Time Complexity - O(n * sum)
123
123
*/
124
124
125
+ //RECURSION USING MEMOIZATION - TOP DOWN
126
+ public static int minPartition (int [] S , int n , int S1 , int S2 , Map <String , Integer > lookup )
127
+ {
128
+ // base case: if list becomes empty, return the absolute
129
+ // difference between two sets
130
+ if (n < 0 ) {
131
+ return Math .abs (S1 - S2 );
132
+ }
133
+
134
+ // construct an unique map key from dynamic elements of the input
135
+ // Note that can uniquely identify the subproblem with n & S1 only,
136
+ // as S2 is nothing but S - S1 where S is sum of all elements
137
+ String key = n + "|" + S1 ;
138
+
139
+ // if sub-problem is seen for the first time, solve it and
140
+ // store its result in a map
141
+ if (!lookup .containsKey (key ))
142
+ {
143
+ // Case 1. include current item in the subset S1 and recur
144
+ // for remaining items (n - 1)
145
+ int inc = minPartition (S , n - 1 , S1 + S [n ], S2 , lookup );
146
+
147
+ // Case 2. exclude current item from subset S1 and recur for
148
+ // remaining items (n - 1)
149
+ int exc = minPartition (S , n - 1 , S1 , S2 + S [n ], lookup );
150
+
151
+ lookup .put (key , Integer .min (inc , exc ));
152
+ }
153
+
154
+ return lookup .get (key );
155
+ }
0 commit comments