1. 程式人生 > >C/C++ | 22-11 棧求組合數

C/C++ | 22-11 棧求組合數

/*
求組合數: 求n個數(1….n)中k個數的組合….
如:combination(5,3)
要求輸出:543,542,541,532,531,521,432,431,421,321,
#include <cstdio>
#include <deque>
#include <algorithm>
#include <iterator>
#include <stdio.h>  
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <assert.h>

using namespace std;
deque<int> result;

void solve(int n, int k) {
	if (result.size() < k) {
		for (int m = n; m >= 1; --m) {
			result.push_back(m);
			solve(m - 1, k);
			result.pop_back();
		}
	}
	else {
		copy(result.begin(), result.end(), ostream_iterator<int>(cout));
		cout << endl;
	}
}

int main(int argc, char *argv[]) {
	int n, k;
	scanf("%d%d", &n, &k);
	solve(n, k);
	return 0;
}