第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在C ++中創(chuàng)建n個(gè)項(xiàng)目的所有可能的k個(gè)組合

在C ++中創(chuàng)建n個(gè)項(xiàng)目的所有可能的k個(gè)組合

慕的地6264312 2019-12-20 11:05:32
從1到有n個(gè)人n。我必須寫(xiě)其產(chǎn)生的代碼,并打印的所有不同的組合k,從這些人n。請(qǐng)解釋用于此的算法。
查看完整描述

3 回答

?
暮色呼如

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊

我假設(shè)您是在詢問(wèn)組合意義上的組合(也就是說(shuō),元素的順序無(wú)關(guān)緊要,所以[1 2 3]與相同[2 1 3])。然后,這個(gè)想法非常簡(jiǎn)單,如果您了解歸納/遞歸:要獲取所有K元素組合,請(qǐng)先從現(xiàn)有人員中選擇組合的初始元素,然后將該初始元素與所有可能的組合“連接” K-1人們從繼承最初元素的元素中產(chǎn)生出來(lái)。


舉例來(lái)說(shuō),假設(shè)我們要從一組5個(gè)人中抽取3個(gè)人的所有組合。然后,可以用2個(gè)人的所有可能組合來(lái)表示3個(gè)人的所有可能組合:


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) }

這是實(shí)現(xiàn)此想法的C ++代碼:


#include <iostream>

#include <vector>


using namespace std;


vector<int> people;

vector<int> combination;


void pretty_print(const vector<int>& v) {

  static int count = 0;

  cout << "combination no " << (++count) << ": [ ";

  for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }

  cout << "] " << endl;

}


void go(int offset, int k) {

  if (k == 0) {

    pretty_print(combination);

    return;

  }

  for (int i = offset; i <= people.size() - k; ++i) {

    combination.push_back(people[i]);

    go(i+1, k-1);

    combination.pop_back();

  }

}


int main() {

  int n = 5, k = 3;


  for (int i = 0; i < n; ++i) { people.push_back(i+1); }

  go(0, k);


  return 0;

}

這是輸出N = 5, K = 3:


combination no 1:  [ 1 2 3 ] 

combination no 2:  [ 1 2 4 ] 

combination no 3:  [ 1 2 5 ] 

combination no 4:  [ 1 3 4 ] 

combination no 5:  [ 1 3 5 ] 

combination no 6:  [ 1 4 5 ] 

combination no 7:  [ 2 3 4 ] 

combination no 8:  [ 2 3 5 ] 

combination no 9:  [ 2 4 5 ] 

combination no 10: [ 3 4 5 ] 


查看完整回答
反對(duì) 回復(fù) 2019-12-20
  • 3 回答
  • 0 關(guān)注
  • 659 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)