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.