-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubset.cpp
More file actions
618 lines (476 loc) Β· 11.7 KB
/
Subset.cpp
File metadata and controls
618 lines (476 loc) Β· 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// 2. Bitmasking (VERY IMPORTANT)
// Formula:
// 2^n subsets
// Example:
// For n=3:
// 000 β []
// 001 β [3]
// 010 β [2]
// 011 β [2,3]
// ...
// Intuition:
// Binary represents inclusion/exclusion.
// 3. Meet in the Middle
// Used when:
// n β€ 40
// brute force too large
// Split array into 2 halves.
// 4. DP on Subsets
// Used in:
// TSP (Travelling Salesman)
// assignment problems
// State:
// dp[mask][i]
// 4. IMPORTANT PROBLEM TYPES (FULL LIST)
// πΉ Subarray problems
// 1. Sum-based
// max subarray sum (Kadane)
// subarray sum = k
// longest subarray with sum β€ k
// 2. Count-based
// count subarrays with condition
// 3. Min/Max window
// smallest window with condition
// 4. Product-based
// subarray product < k
// πΉ Subset problems
// 1. Generate all subsets
// power set
// 2. Target sum
// subset sum problem
// 3. Partition problems
// equal partition
// subset difference
// 4. Combination sum
// pick elements multiple times
// 5. ADVANCED INTUITION LAYER
// π₯ Why sliding window works?
// Because:
// constraints are monotonic β expanding or shrinking preserves validity
// π₯ Why Kadane works?
// Because
// optimal subarray ending at i depends only on i-1
// π₯ Why prefix sum works?
// Because:
// cumulative information removes recomputation
// π₯ Why bitmask works?
// Because:
// every subset is a binary decision tree compressed into integers
// 7. HOW TO IDENTIFY SOLUTION FAST
// Ask:
// Q1: Is it continuous?
// β YES β subarray
// Q2: Need all combinations?
// β YES β subset
// Q3: Is sum involved?
// β prefix / hashmap
// Q4: Is it max/min window?
// β sliding window
// Q5: exponential choices?
// β backtracking / bitmask
// π₯ 1. GENERATE ALL SUBSETS (POWER SET)
// πΉ Problem
// Generate all subsets of:
// arr = [1, 2, 3]
// π₯ Mathematical Idea
// Each element has 2 choices:
// include OR exclude
// So total subsets:
// 2^n
// π₯ Algorithm
// β Backtracking (DFS)
// β OR Bitmasking (binary representation)
#include<bits/stdc++.h>
using namespace std;
void solve(int i,vector<int>&arr, vector<int>&temp,vector<vector<int>>&result){
if(i==arr.size()){
result.push_back(temp);
return;
}
//include
temp.push_back(arr[i]);
solve(i+1,arr,temp,result);
//exclude
temp.pop_back();
solve(i+1,arr,temp,result);
}
int main(){
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
vector<int>temp;
vector<vector<int>>result;
solve(0,arr,temp,result);
//print all subsets
for(auto subset:result){
for(auto num:subset){
cout<<num<<" ";
}
cout<<endl;
}
return 0;
}
//π₯ 2. SUBSET SUM (TARGET SUM)
// πΉ Problem
// Find subsets whose sum = K
// πΉ Mathematical Idea
// Similar to generating subsets, but check sum condition
// πΉ Algorithm
// β Backtracking (DFS)
// β OR Bitmasking (binary representation)
// Check if subset exists with sum = K
// [3, 4, 5], K = 9
// π₯ Mathematical Idea
// We try all combinations of:
// pick or not pick
//We search:
//sum(subset) = K
//sum(subset) = K - arr[i]
//sum(subset) = K - arr[i] - arr[j]
#include<bits/stdc++.h>
using namespace std;
bool solve(int i,vector<int>&arr,int sum){
if(sum==0){
return true;
}
if(i==arr.size()|| sum<0){
return false;
}
// Include current element
if(solve(i+1,arr,sum-arr[i])){
return true;
}
// Exclude current element
if(solve(i+1,arr,sum)){
return true;
}
return false;
}
int main(){
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
int k;
cin>>k;
if(solve(0,arr,k)){
cout<<"subset exits with sum = "<<k<<endl;
} else {
cout<<"No subset found with sum = "<<k<<endl;
}
return 0;
}
// π₯ 3. EQUAL PARTITION PROBLEM
// πΉ Problem
// Can we split array into 2 equal sum subsets?
// [1, 5, 11, 5]
// π₯ Mathematical Idea
// Let total sum = S
// We need:
// S1 + S2 = S
// S1 = S2
// β S1 = S/2
// So problem becomes:
// π subset sum = S/2
// π₯ Algorithm
// β Dynamic Programming (0/1 Knapsack style)
// π₯ Step 2: Why 0/1 Knapsack?
// Because:
// Each element has only 2 choices:
// Take it (1 time)
// OR
// Don't take it
// This is exactly:
// π 0/1 Knapsack property
// β0β β donβt take
// β1β β take
// π₯ Step 3: DP State Definition
// We define:
// dp[i][j] = can we make sum j using first i elements?
// π₯ Step 4: Transition (Core Logic)
// For each element:
// Two choices:
// 1. NOT TAKE
// dp[i][j] = dp[i-1][j]
// 2. TAKE (only if possible)
// dp[i][j] = dp[i-1][j - arr[i-1]]
// π₯ Final Transition
// dp[i][j] = dp[i-1][j] OR dp[i-1][j - arr[i-1]]
// π₯ Step 5: Base Cases
// dp[i][0] = true (sum 0 always possible)
// dp[0][j] = false (no elements β can't make sum > 0)
// π₯ Step 6: DP Table Intuition
// We try to build sum 0 β 11
// Letβs visualize important steps:
// Array:
// [1, 5, 11, 5]
// After considering 1:
// Possible sums:
// 0, 1
// After considering 5:
// 0, 1, 5, 6
// After considering 11:
// 0, 1, 5, 6, 11, 12, 16, 17
// π We already got 11 β SUCCESS
#include<bits/stdc++.h>
using namespace std;
bool canPartition(vector<int>&arr){
int sum= accumulate(arr.begin(),arr.end(),0);
// If total sum is odd, can't partition into 2 equal subsets
if(sum%2!=0){
return false;
}
int target=sum/2;
int n=arr.size();
vector<vector<bool>>dp(n+1,vector<bool>(target+1,false));
// Base case: sum 0 is always possible
for(int i=0;i<=n;i++){
dp[i][0]=true;
}
// Fill the DP table
for(int i=1;i<=n;i++){
for(int j=1;j<=target;j++){
// Not take the current element
dp[i][j]=dp[i-1][j];
// Take the current element (only if it doesn't exceed the sum)
if(j>=arr[i-1]){
dp[i][j]=dp[i][j] || dp[i-1][j-arr[i-1]];
}
}
}
return dp[n][target];
}
int main(){
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
if(canPartition(arr)){
cout<<"array can participate in two equal partitions"<<endl;
} else {
cout<<"array cannot participate in two equal partitions"<<endl;
}
}
// π₯ Step 9: Space Optimization (IMPORTANT)
// We can reduce to 1D DP:
// dp[j] = can we make sum j using any subset of elements so far?
// Transition becomes:
// dp[j] = dp[j] OR dp[j - arr[i-1]]
// π₯ Why backward loop?
// to avoid reusing same element multiple times
// π This ensures 0/1 behavior
// π FINAL INTUITION (GOLD LINE)
// Equal Partition = Subset Sum = 0/1 Knapsack
// Because:
// π Each element can be used only once
// π We are trying to fill exact capacity (S/2)
#include<bits/stdc++.h>
using namespace std;
bool canParticipate(vector<int>&arr){
int sum=accumulate(arr.begin(),arr.end(),0);
if(sum%2!=0){
return false;
}
int target=sum/2;
vector<bool>dp(target+1,false);
dp[0]=true;
for(int i=0;i<arr.size();i++){
for(int j=target;j>=arr[i];j--){
dp[j]=dp[j] || dp[j-arr[i]];
}
}
return dp[target];
}
int main(){
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
if(canParticipate(arr)){
cout<<"arr can participate in equal partitions"<<endl;
} else {
cout<<"arr cannot participate in equal partitions"<<endl;
}
return 0;
}
// π₯ Intuition above
// π Instead of splitting into 2 groups:
// We just check if ONE subset = half sum exists
// π₯ 4. MINIMUM SUBSET DIFFERENCE
// πΉ Problem
// Divide array into 2 subsets with minimum difference
// [1, 6, 11, 5]
// π₯ Mathematical Idea
// Let total sum = S
// If subset sum = S1:
// S2 = S - S1
// diff = |S - 2*S1|
// So:
// π minimize difference β S1 closest to S/2
// π₯ Algorithm
// β DP (Subset Sum + Optimization)
#include<bits/stdc++.h>
using namespace std;
int minDifference(vector<int>&arr){
int sum=accumulate(arr.begin(),arr.end(),0);
int n=arr.size();
vector<vector<bool>>dp(n+1,vector<bool>(sum+1,false));
for(int i=0;i<=n;i++){
dp[i][0]=true;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=sum;j++){
dp[i][j]=dp[i-1][j];
if(j>=arr[i-1]){
dp[i][j]=dp[i][j]|| dp[i-1][j-arr[i-1]];
}
else{
dp[i][j]=dp[i-1][j];
}
}
}
int minDiff=INT_MAX;
for(int j=0;j<=sum/2;j++){
if(dp[n][j]){
minDiff=min(minDiff,abs(sum-2*j));
}
}
return minDiff;
}
int main(){
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"Minimum subset difference is: "<<minDifference(arr)<<endl;
return 0;
}
// π₯ Intuition
// π We donβt try all partitions directly
// We compute all possible subset sums and pick the best split
// π₯ 5. COMBINATION SUM (UNLIMITED PICKS)
// πΉ Problem
// Find all combinations that sum to target:
// [2, 3, 6, 7], target = 7
// π₯ Mathematical Idea
// Unlike subset:
// π elements can be reused infinitely
// So:
// state does NOT move forward when picked
// π₯ Algorithm
// β Backtracking (DFS)
// π₯ 1. CORE MATHEMATICAL MODEL
// This problem is NOT just recursion.
// π It is solving:
// 2x + 3y + 6z + 7w = 7
// Where:
// x, y, z, w β₯ 0 (can repeat elements)
// π‘ This is called:
// π Integer Linear Combination Problem
// We are finding:
// combinations of numbers that sum to target
// π₯ 2. WHY βUNLIMITED PICKSβ?
// Because:
// x, y, z, w can be ANY non-negative integer
// Example:
// 2 + 2 + 3 = 7 β x=2, y=1
// 7 = 7 β w=1
// π₯ 3. GEOMETRIC INTUITION
// Think of it like:
// π You are walking on a number line from 0 β 7
// Allowed steps:
// +2, +3, +6, +7
// Goal:
// π Reach exactly 7
// π‘ Paths:
// 0 β 2 β 4 β 7 (2,2,3)
// 0 β 7 (7)
// π₯ 4. DECISION TREE (MATHEMATICAL FORM)
// At each step:
// f(target) =
// f(target - 2)
// f(target - 3)
// f(target - 6)
// f(target - 7)
// π₯ Recurrence Relation
// f(T) = Ξ£ f(T - arr[i])
// π This is like:
// coin change
// partition function
// π₯ 5. WHY BACKTRACKING WORKS
// Because:
// π We explore ALL valid integer solutions
// Constraints:
// target >= 0
// Stop when:
// target == 0 β valid solution
// target < 0 β invalid
// π₯ 6. KEY MATHEMATICAL PROPERTY
// πΉ Order does NOT matter
// [2,2,3] == [3,2,2]
// So we enforce:
// π non-decreasing order
// π₯ Trick:
// We ensure:
// we donβt go backward in array
// This avoids duplicates mathematically.
// π₯ 7. CORE BACKTRACKING EQUATION
// f(i, target) =
// f(i, target - arr[i]) // take again
// f(i+1, target) // skip
// π₯ WHY STAY AT SAME INDEX?
// Because:
// element can be reused infinitely
// Mathematically:
// x can be 0,1,2,3...
#include<bits/stdc++.h>
using namespace std;
void solve(int i,vector<int>&arr,int target,vector<int>&temp,vector<vector<int>>&result){
if(target==0){
result.push_back(temp);
return;
}
if(i==arr.size()|| target<0){
return;
}
//take current element
if(arr[i]<=target){
temp.push_back(arr[i]);
solve(i,arr,target-arr[i],temp,result);
temp.pop_back();
}
//skip current element
solve(i+1,arr,target,temp,result);
}
int main(){
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
int target;
cin>>target;
vector<int>temp;
vector<vector<int>>result;
solve(0,arr,target,temp,result);
//print all combinations
for(auto num:result){
for(auto val:num){
cout<<val<<" ";
}
cout<<endl;
}
return 0;
}