Two integers n and m, arbitrarily taking several numbers from the sequence 1,2,3.......N, making them and M

Source: Internet
Author: User

/* Input two numbers m and N, select several of these numbers from the sequence 1,2,3,4,..... N and for M, find all of such combinations */void findsum (int m,intn,vector<int>& vec) {    if (M < 0 | | n < 0)     return;    if (M = = 0)    {         Vector<int>::iterator ITR = Vec.begin ();                  for (; ITR! = Vec.end (); itr++)          cout<<*itr<< "";          cout<<endl;          return;         }    Vec.push_back (n); Typical knapsack problem    findsum (M-N,N-1,VEC);//put an element in the remaining element to meet the remaining requirements    vec.pop_back ();//do not put elements in the current period to  meet all requirements in the remaining elements    findsum (M,n-1,vec);    } int main () {   vector<int> vec;   Findsum (9,10,vec);   System ("pause");   return 0;    }
This is a typical knapsack problem, for such problems, the main thing is to clear the mind, is not in line with the knapsack principle, and then find the appropriate solution. At the same time you need to understand how to deal with boundary problems and when to return. If sum is 0, the explanation already has a solution, if there is no suitable solution, then n or M has reached the boundary, such as M is too large, there is no solution. Also needs to be returned.


At the same time if you do not understand the knapsack problem, there is a way to solve, is not to choose from an array of elements, but the selection of the number of elements are different, like not from all combinations of a sequence to find a qualifying sequence, that is, if you know how to find a sequence of all combinations, Then select the matching criteria from these combinations, use a flag-bit array, and then the data that is marked and whether it is the required solution.





Two integers n and m, arbitrarily taking several numbers from the sequence 1,2,3.......N, making them and M

Contact Us

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.