输出组合 之 哈理工oj 2179

/*
给出一个正整数N,从集合{1,2,3..N} 中找出所有大小为k的子集, 并按照字典序从小到大输出。
*/
#define _CRT_SECURE_NO_WARNINGS
//#define HOME

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <locale>
#include <cmath>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MaxN = 15;

int N, k;
vector<int> arr(MaxN, 0);
vector<vector<int> > combine;

void dfs(int num, int pos) {
    if (num == k) {
        combine.push_back(arr);
        return;
    }
    for (int i = pos; i < N; ++i) {
        arr[num] = i;
        dfs(num + 1, i + 1);
    }
}

int main() {
#ifdef HOME
    freopen("in", "r", stdin);
    //freopen("out", "w", stdout);
#endif

    int T;
    cin >> T;
    while (T--) {
        cin >> N >> k;
        dfs(0, 0);
        for (int i = 0; i < combine.size(); ++i) {
            for (int j = 0; j < k; ++j) {
                cout << combine[i][j] + 1;
                if (j != (k - 1)) {
                    cout << ' ';
                }
            }
            cout << endl;
        }
        combine.clear();
    }

    
#ifdef HOME
    cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
#endif
    return 0;
}
原文地址:https://www.cnblogs.com/shijianming/p/4923800.html