Enter two integer values N and m to find all combinations of integers 1 to n and M
Cases:
Input: n=10 m=10
Output:
1 2 3 4
1 2 7
1 3 6
1 4 5
1 9
2 3 5
2 8
3 7
4 6
10
Ideas:
1. The full arrangement of the output 1-n
2. Restrictions: The first I item is equal to M, then outputs the first I, otherwise does not output
3. After searching for the value J, no further search is no longer included J (after searching for the element containing 1, subsequent searches no longer search for element 1 After searching for elements containing the value 2 no longer searching for element 2)
The code is as follows:
#include <stdio.h> #include <iostream> using namespace std;//print result void Print_res (
int *a,int N) {for (int i=1;i<n;i++) printf ("%d", a[i]);
printf ("\ n");
}//Recursive search for void dfs (int *data,int *index,int step,int n,int m,int sum) {int i;
if (Sum > M)//no longer looks for return;
else if (sum = = m)//output {print_res (data,step);
Return
} for (i=data[step-1]+1;i<=n;i++)//Key {if (index[i]==0)//The element has not been used {data[step]=i;
Index[i]=1;
DFS (Data,index,step+1,n,m,sum+i);
index[i]=0;
}} return;
} int main () {int m,n;
cin>>n>>m;
int *index=new int[n+1];
int *data=new int[n+1];
for (int i=0;i<n+1;i++) {index[i]=0;
data[i]=0;
} dfs (data,index,1,n,m,0);
Delete [] index;
delete [] data;
return 0; }