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

#include <iostream>
#include <vector>
#include <queue>

using namespace std;


vector<vector<int> > Subsets(vector<int> s)
{
    int n = s.size();
    sort(s.begin(), s.end());
    
    vector<vector<int> > subs;
    queue<vector<int> > vQueue;
    subs.push_back(vector<int>()); //Empty subset

    for (int i = 0; i < n; ++i)
        vQueue.push(vector<int>(1,i));

    while(!vQueue.empty())
    {
        vector<int>& subIndics = vQueue.front();
        subs.push_back(vector<int>());
        vector<int>& v = subs.back();

        for (int i = 0; i < subIndics.size(); ++i)
            v.push_back(s[subIndics[i]]);
        
        int next = subIndics.back()+1;
        subIndics.push_back(0);
        for (int i = next; i < n; ++i)
        {
            subIndics.back() = i;
            vQueue.push(subIndics);
        }

        vQueue.pop();
    }

    return subs;
}

void PrintVV(vector<vector<int> > v)
{
    cout << '\n';
	int size = 0;
    for (int i = 0; i < v.size(); ++i)
    {
		cout << ++size << ':';
        if (v[i].size() <= 0)
        {
            cout << "[empty]\n";
            continue;
        }

        cout << '[';
        for (int j = 0; j < v[i].size(); ++j)
            cout << v[i][j] << ',';

        cout << ']' << endl;
    }

    cout << endl;
}

vector<int> Array2Vector(int A[], int n)
{
    vector<int> v;
    for (int i = 0; i < n; ++i)
    {
        v.push_back(A[i]);
        cout << A[i] << ',';
    }

    cout << endl;
	
	return v;
}

int main(int argc, char** argv)
{
    int A[] = {1, 3, 5, 7};
    int n = sizeof(A)/sizeof(int);

    vector<int> v = Array2Vector(A, n);

    PrintVV(Subsets(v));
    return 0;
}
View Program Text


Test Status