IT公司100題-1-二叉樹轉換為雙鏈表

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   strong   for   問題   

問題描述:輸入兩個整數n 和m,從數列1,2,3,…,n 中隨意取幾個數, 使其和等於m,將所有可能的組合都列印出來。 分析:利用遞迴的思路,對於1,2,3,…,n 中的任意一個數,要麼選,要麼不選。遞迴下去,直到其和等於m時,輸出。 

解答:

 

 1 // 21.cc 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5  6 void print(int* aux, int n) { 7     for (int i = 0; i < n; i++) 8         if (aux[i]) 9             cout << i << " ";10     cout << endl;11 }12 13 void helper(int m, int cur, int* aux, int n) {14     if (m == 0)15         print(aux, n);16     if (m <= 0 || cur == n)17         return;18 19     // 不選cur20     helper(m, cur + 1, aux, n);21 22     // 選cur23     aux[cur] = 1;24     helper(m - cur, cur + 1, aux, n);25     aux[cur] = 0;  // 回溯26 }27 28 void find_combi(int n, int m) {29     if (n > m) 30         find_combi(m, m);31 32     int* aux = new int[n];  // aux[i] = 1,表示選擇i33     memset(aux, 0, n * sizeof(int));34     helper(m, 0, aux, n);35 }36 37 int main() {38     int n, m;39     cout << "input n and m:" << endl;40     cin >> n >> m;41     find_combi(n, m);42     return 0;43 }

 

$ ./a.exeinput n and m:6 31 20 1 231 20 30 1 2

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.