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

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

using namespace std;


vector<vector<int> > Combinations(int n, int k)
{   
    vector<vector<int> > subs;
    queue<vector<int> > vQueue;

	vQueue.push(vector<int>());

    while(!vQueue.empty())
    {
        vector<int>& sub = vQueue.front();
        
        int next = sub.size() > 0? sub.back()+1 : 1;
        sub.push_back(0);
        for (int i = next; i <= n; ++i)
        {
            sub.back() = i;
            if (sub.size() == k)
                subs.push_back(sub);
            else
                vQueue.push(sub);
        }

        vQueue.pop();
    }

    return subs;
}

void PrintVV(vector<vector<int> > v)
{

    int n = 1;
    for (int i = 0; i < v.size(); ++i)
    {
        cout << n++ << ": [";
        for (int j = 0; j < v[i].size(); ++j)
            cout<< v[i][j] << ',';
        cout << "]\n";
    }

    cout << endl;
}
int main(int argc, char** argv)
{
    PrintVV(Combinations(10,3));
    return 0;
}
View Program Text


Test Status