forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subsets.cpp
66 lines (57 loc) · 1.19 KB
/
subsets.cpp
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
//C++ Program to print all subsets of a given distinct array of positive integers
#include <bits/stdc++.h>
using namespace std;
void GetSubsets(vector<int> inputArray, vector<int> subsetArray, int pos)
{
if (pos == inputArray.size())
{
//the input array has been traversed when pos = array size
cout << "[";
for (int i = 0; i < subsetArray.size(); i++)
{
if (subsetArray[i] != 0) //ignoring empty values
cout << subsetArray[i] << ",";
}
cout << "]\n";
}
else
{
GetSubsets(inputArray, subsetArray, pos + 1); //Recursion tree branch 1
subsetArray[pos] = inputArray[pos];
GetSubsets(inputArray, subsetArray, pos + 1); //Recursion tree branch 2
}
}
//DRIVER FUNCTION
int main()
{
int size;
cout << "Enter size of the array: ";
cin >> size;
vector<int> inputArray(size); //initializing input array with user-given size
for (int i = 0; i < size; i++)
{
cin >> inputArray[i];
}
vector<int> subsetArray(size); //empty array for storing subsets
cout << "[";
GetSubsets(inputArray, subsetArray, 0); //prints the subsets
cout << "]";
}
/*Sample IO
Input:
3
1 2 3
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
TIME COMPLEXITY - O(2^n)
SPACE COMPLEXITY - O(n)
/*