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, determine that if nm is used, the number of n greater than m cannot be involved in the combination, and then set it to nm; 2. Add the maximum number n to the nm,
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 the nm is used, the number of n greater than m cannot be involved in the combination, and n = m; 2. add the maximum number n and n = m,
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
[Java]View plaincopyprint?
- Public class s21 {
- Private static upload list List = new external list ();
- /**
- * 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 output is successful;
- * 3. Solve n in two cases: n is not added, n = n-1, m = m, and recursion;
- * 4. Add n, n = n-1, m = m-n, and recursion.
- * 5. End.
- * @ Param sum
- * @ Param n
- */
- Public static void findSum (int sum, int n)
- {
- If (n <1 | sum <1)
- Return;
- If (sum> n)
- {
- List. add (n );
- FindSum (sum-n, n-1); // Add n, n = n-1, m = m-n
- List. pop ();
- FindSum (sum, n-1); // n is not added, n = n-1, m = m
- }
- Else
- {
- System. out. print (sum); // sum <n, directly output n to meet
- For (int I = 0; I <list. size (); I ++)
- System. out. print ("" + list. get (I ));
- System. out. println ();
- }
- }
- /**
- * @ Param args
- */
- Public static void main (String [] args ){
- // TODO Auto-generated method stub
- Int sum = 10;
- Int n = 6;
- FindSum (sum, n );
- }
- }