### kushal.p1699's blog

By kushal.p1699, history, 3 months ago, Hi all, I'm so excited to write my first blog here.

Last week I was helping my friend in tracing the recursion problem called Generating subset. He had the code snippet, but he was not able to understand the flow of the program. So, I tried to explain the logic to him. I'm happy that, my explanation made him clear on his doubts. I thought of sharing my explanation on tracing this problem by writing a new blog.

Problem statement:
Generate the subsets of given N elements using recursion.

Input:
1 2 3

output:
1 2 3
1 2
1 3
1
2 3
2
3

Explanation:
Subsets of [1,2,3] is null, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}.

code:

#include <bits/stdc++.h>
using namespace std;

vector<int> subset;
void solve(int a[], int n, int index) {
if(index == n){
// print the subset
for(int i=0; i<subset.size(); i++){
cout << subset[i] << " ";
}
cout << "\n";
}else{
subset.push_back(a[index]);
solve(a, n, index+1);
subset.pop_back();
solve(a, n, index+1);
}
}

int main() {
int a[] = {1, 2, 3};
int n = sizeof(a)/sizeof(a);
int startIndex = 0;
solve(a, n, startIndex);
return 0;
}


My explanation of this program is given below. This is my first blog ever in my life. If you find any mistakes or you have any suggestions, please let me know. So that I can improve it form next time.

Thank you. #c++, #cp,