Enter two integers n and m, from series 1,2,3.......N take a few numbers in a random ,
Make it and equal to m, require that all possible combinations of them be listed
//the essence of the problem is the 01 backpack, which just fills up. //because there are many groups of solutions, it is usually solved by recursion//for each n (n can be from N to 1)//if n is taken, then the sub-problem becomes find (n-1,m-n);//if n is not taken, then the sub-problem becomes find (n-1,m);#include<stdio.h>intLength//since the length of the flag is not good in the function, we set it as a global variablevoidFindcom (intNintMint*flag) { if(n<1|| m<1)return;//boundary, the smallest number in the test instructions is 1 if(n>m) n=m;//pruning, greater than the number of m without consideration if(n==m) {Flag[n-1]=1;//mark the last number as 1;//The number that will be marked as 1, the output for(intI=0; i<length;i++) if(flag[i]==1) printf ("%d\t", i+1); printf ("\ n"); Flag[n-1]=0;//Backtracking} flag[n-1]=1; Findcom (n-1, M-n,flag);//to nFlag[n-1]=0; Findcom (n-1, M,flag);//do not n}intMain () {intn,m; scanf ("%d%d",&n,&m); Length=n;//The n in the function is variable, so length is to be placed in main intFlag[length];//Tag Arrayfindcom (N,m,flag); return 0;}
Data structure and algorithm surface test questions 80 (21)