IT company 100 question-1-binary tree conversion to double-chain table

Source: Internet
Author: User
Problem description:Input two integers, N and m, from the series 1, 2, 3 ,..., N is random, so that the sum is equal to m and all possible combinations are printed out. Analysis:Using recursive thinking, for 1, 2, 3 ,..., Any number in N is either selected or not. Recursion continues until its sum is equal to M.

Answer:

 

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) is not selected ); 21 22 // select cur23 aux [cur] = 1; 24 helper (m-cur, cur + 1, aux, n); 25 aux [cur] = 0; // backtracking 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, indicates 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

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.