Question 21: programming, input two integers n and m, from Series 1, 2, 3 ,...... N is random, so that the sum is equal to M. All possible combinations are required. It is actually a backpack problem.
Solution:
1. First, it is judged that if n> m, the number of N greater than m cannot be involved in the combination, and n = m is set at this time;
2. If the maximum number N is added and n = m, the condition is met and the result is output;
3. solve N in two cases: (1) N is not added, n = n-1; M = m; recursion; (2) N is added, take n = N-1l, M = m-N, and Recursion
Public class S21 {<br/> Private Static Sequence List <integer> List = new sequence list <integer> (); <br/>/** <br/> * solution: <br/> * 1. first, it is judged that if n> m, the number of N greater than m cannot be involved in the combination, and n = m is set at this time; <br/> * 2. if n is added to the maximum number N and n = m, the condition is met and the result is output. <br/> * 3. solve N in two cases: N is not added, n = n-1, M = m, recursion; <br/> * 4. add N, take n = n-1, M = m-N, recursive. <Br/> * 5. End. <Br/> * @ Param sum <br/> * @ Param n <br/> */<br/> Public static void findsum (INT sum, int N) <br/>{< br/> If (n <1 | sum <1) <br/> return; <br/> If (sum> N) <br/>{< br/> list. add (n); <br/> findsum (Sum-N, N-1); // Add n, n = n-1, M = m-n <br/> list. pop (); <br/> findsum (sum, n-1); // n is not added, n = n-1, M = m <br/>}< br/> else <br/>{< br/> system. out. print (SUM); // sum <n, directly output n to meet <br/> for (INT I = 0; I <list. size (); I ++) <br/> system. out. print ("" + list. get (I); <br/> system. out. println (); <br/>}< br/>/** <br/> * @ Param ARGs <br/> */<br/> Public static void main (string [] ARGs) {<br/> // todo auto-generated method stub <br/> int sum = 10; <br/> int n = 6; <br/> findsum (sum, n); <br/>}< br/>