在C ++中创建n个项目的所有可能的k个组合

1到有n个人n。我必须写其产生的代码,并打印的所有不同的组合k,从这些人n。请解释用于此的算法。



慕的地6264312
浏览 630回答 3
3回答

暮色呼如

我假设您是在询问组合意义上的组合(也就是说,元素的顺序无关紧要,所以[1 2 3]与相同[2 1 3])。然后,这个想法非常简单,如果您了解归纳/递归:要获取所有K元素组合,请先从现有人员中选择组合的初始元素,然后将该初始元素与所有可能的组合“连接” K-1人们从继承最初元素的元素中产生出来。举例来说,假设我们要从一组5个人中抽取3个人的所有组合。然后,可以用2个人的所有可能组合来表示3个人的所有可能组合:comb({ 1 2 3 4 5 }, 3) ={ 1, comb({ 2 3 4 5 }, 2) } and{ 2, comb({ 3 4 5 }, 2) } and{ 3, comb({ 4 5 }, 2) }这是实现此想法的C ++代码:#include <iostream>#include <vector>using namespace std;vector<int> people;vector<int> combination;void pretty_print(const vector<int>& v) {&nbsp; static int count = 0;&nbsp; cout << "combination no " << (++count) << ": [ ";&nbsp; for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }&nbsp; cout << "] " << endl;}void go(int offset, int k) {&nbsp; if (k == 0) {&nbsp; &nbsp; pretty_print(combination);&nbsp; &nbsp; return;&nbsp; }&nbsp; for (int i = offset; i <= people.size() - k; ++i) {&nbsp; &nbsp; combination.push_back(people[i]);&nbsp; &nbsp; go(i+1, k-1);&nbsp; &nbsp; combination.pop_back();&nbsp; }}int main() {&nbsp; int n = 5, k = 3;&nbsp; for (int i = 0; i < n; ++i) { people.push_back(i+1); }&nbsp; go(0, k);&nbsp; return 0;}这是输出N = 5, K = 3:combination no 1:&nbsp; [ 1 2 3 ]&nbsp;combination no 2:&nbsp; [ 1 2 4 ]&nbsp;combination no 3:&nbsp; [ 1 2 5 ]&nbsp;combination no 4:&nbsp; [ 1 3 4 ]&nbsp;combination no 5:&nbsp; [ 1 3 5 ]&nbsp;combination no 6:&nbsp; [ 1 4 5 ]&nbsp;combination no 7:&nbsp; [ 2 3 4 ]&nbsp;combination no 8:&nbsp; [ 2 3 5 ]&nbsp;combination no 9:&nbsp; [ 2 4 5 ]&nbsp;combination no 10: [ 3 4 5 ]&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP