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