You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: searching.md
+52-1Lines changed: 52 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -172,7 +172,58 @@ Let us consider the problem of calculating the number of paths in an n x n grid
172
172
173
173
Meet in the middle is a technique where the search space is divided into two parts of about equal size. A separate search is performed for both of the parts, and finally the results of the searches are combined.
174
174
175
-
For example, suppose that the list is \[2,4,5,9\] and x = 15. First, we divide the list into A = \[2,4\] and B = \[5,9\]. After this, we create lists SA = \[0,2,4,6\] and SB = \[0,5,9,14\]. \(SA is total subset sum possible in A\) Next we can find original problem solution by using hashmap SA\[i\] + SA\[j\] = targ.
175
+
### [Partition Array Into Two Arrays to Minimize Sum Difference](https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/description/)
176
+
177
+
```cpp
178
+
/** Here naive solution was to get all possible subsets through bitmanipulation 2^(2n) for the cases where popcount is n get the sum.
179
+
However total time complexity of 2^2n is 2^30 will give TLE.
180
+
181
+
Solution use meet in middle approach, divide the array in two part [0, n/2 - 1] [n/2, n-1]
182
+
Now, find all subset which will be 2*2^n i.e. 2^16 which is within limit. Grouping those subsets in terms of how many elements taken.
183
+
Now do a loop on how much to take from left and get its possible sums and do a lower bound on right possibilities.
184
+
185
+
*/
186
+
classSolution{
187
+
public:
188
+
int minimumDifference(vector<int>& nums){
189
+
int totalSum = accumulate(nums.begin(), nums.end(), 0), n = nums.size();
190
+
191
+
function<vector<vector<int>>(int, int)> findAllSubsets = [&](int l, int r) -> vector<vector<int>>{
192
+
int len = r - l + 1;
193
+
vector<vector<int>> res(len + 1);
194
+
for (int i = 0; i < (1 << len); ++i){
195
+
int sum = 0;
196
+
for (int j = 0; j < len; ++j){
197
+
if (i&(1<<j)) sum += nums[l + j];
198
+
}
199
+
res[__builtin_popcount(i)].push_back(sum);
200
+
}
201
+
return res;
202
+
};
203
+
204
+
auto left = findAllSubsets(0, n/2 - 1);
205
+
auto right = findAllSubsets(n/2, n - 1);
206
+
207
+
int res = INT_MAX;
208
+
for (int takeLeft = 0; takeLeft <= n/2; ++takeLeft){
0 commit comments