# Programming, input two integers n and m, from the series 1, 2, 3 ,...... N is random, so that the sum is equal to M. All possible combinations are required (solve the knapsack problem)

Source: Internet
Author: User

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/>

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.