-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Code for generation of subsets using recursion and backtracking
- Loading branch information
1 parent
50ac396
commit 2c8c10a
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
Generation_of_Subsets_using_Recursion_and_Backtracking.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
#include <bits/stdc++.h> | ||
#include<stdio.h> | ||
using namespace std; | ||
|
||
vector<vector<int> > allSubsets; | ||
|
||
void generate(vector<int> &subset, int i, vector<int> &nums){ | ||
if(i == nums.size()){ | ||
allSubsets.push_back(subset); | ||
return; | ||
} | ||
|
||
// ith element not in subset | ||
generate(subset, i+1, nums); | ||
|
||
// ith element in subset | ||
subset.push_back(nums[i]); | ||
generate(subset, i+1, nums); | ||
subset.pop_back(); | ||
} | ||
|
||
int main(){ | ||
int n; | ||
cin >> n; | ||
vector<int> nums(n); | ||
for(int i = 0 ; i < n; ++i){ | ||
cin >> nums[i]; | ||
} | ||
vector<int> empty; | ||
generate(empty, 0, nums); | ||
for(auto subset : subsets){ | ||
for(auto ele : subset){ | ||
cout << ele << " "; | ||
} | ||
cout << endl; | ||
} | ||
} |