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