# Two integers, n and m, take a few random numbers from the series 1, 2, 3 ...... n to make it m, Series 3... n

Source: Internet
Author: User

Two integers, n and m, take a few random numbers from the series 1, 2, 3 ...... n to make it m, Series 3... n

`/* Enter two numbers m and n, from the numbers 1, 2, 3, 4 ,..... n: select the sum of the numbers (m) to find all 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 place the elements in the current period. The remaining elements meet all requirements. FindSum (m, n-1, vec);} int main () {vector <int> vec; findSum (9,10, vec); system ("pause"); return 0 ;}`
This is a typical type of backpack problem. For this type of problem, the main thing is to clarify whether the thought is in line with the backpack principle and then find a proper solution. At the same time, you need to understand how to handle the boundary issue and when to return it. If sum is 0, it indicates there is already a solution. If there is no suitable solution, then n or m has reached the boundary. For example, M is too large to have a solution. You also need to return.

At the same time, if you do not understand the knapsack problem, there is a way to solve it. Isn't it just to select some elements from an array, but the number of elements selected is different, it does not look like finding a qualified series from all the combinations of a series. That is to say, if you know how to find all the combinations of a series, you can select the qualified combinations from these combinations, use an array of flag spaces, and check whether the sum of labeled data is required.

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.