Question 21st:
Enter two integers, N and m, from the series 1, 2, 3 ....... N returns a few random numbers to make it equal to M. All possible combinations must be listed.
When I saw such a question, I had no idea where to start. By collecting information online, I finally got it done.
Let's take a look at the following ideas:
Given N and m;
1. Determine
N * (n + 1)/2And
MRelationship
IfN * (n + 1)/2> mIf there is a drama, we can continue,
IfN * (n + 1)/2 <m
No, because1, 2,... nThe sum of all numbers is notMBig. Therefore, log out directly.
2. Then find the number in a loop.
The starting condition of the loop must be fromI = 1Start, but where does it end?
The condition for loop is:I <n & I <m/2Is the focus,I <nYes. The key is later.I <m/2Because ifI
> = M/2IA large numberIThe sum must be greaterM.
3. Recursive Solution
Code:
Public class algorithm21_0 {static void getallcomp (int n, int m) {string pre = m + "="; int themax = (1 + n) * n/2; if (themax <m) {system. out. println ("this number does not exist! ");} Else {for (INT I = 1; I <n & I <= m/2; I ++) {// count from 1, print the combination of two numbers, and the two numbers are not equal if (I! = M-I & (M-I) <= N) {system. out. println ("here:" + pre + I + "+" + (m-I); // continue;} // call recursion, continue to obtain the combination of more than 2 numbers gettheresult (m-I, pre + I, I, n) ;}// call recursion and continue to obtain the combination of more than 2 numbers, J is the number used in the combination, so the number is greater than this number. Static void gettheresult (int m, string pre, Int J, int N) {for (INT I = J + 1; I <n & I <= m/2; I ++) {if (I! = M-I & (M-I) <= n) system. out. println ("Fuck:" + pre + "+" + I + "+" + (m-I); gettheresult (m-I, pre + "+" + I, i, n) ;}} public static void main (string [] ARGs) {getallcomp (10, 11 );}}