Given a set of candidate numbers (C) And a target number (T), Find all unique combinations inCWhere the candidate numbers sumsT.
TheSameRepeated number may be chosen fromCUnlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (A1,A2 ,... ,AK) must be in Non-descending order. (ie,A1 ≤A2 ≤... ≤AK ).
- The solution set must not contain duplicate combinations.
For example, given candidate set2,3,6,7And target7,
A solution set is:
[7]
[2, 2, 3]
Note that the data given by the question may be out of order, because each element in the set can be used once or multiple times, but there cannot be repeated combinations in the answer, in addition, the elements in the combination must be in a non-descending order. Therefore, at the beginning, you must sort candidates and deduplicate the elements, and then perform a deep search for each element.
There are two options in each step of deep search. We can select or disable the k-th element.
1 class solution {2 public: 3 vector <int> combinationsum (vector <int> & candidates, int target) {4 vector <int> path; // storage solution 5 allpath. clear (); 6 sort (candidates. begin (), candidates. end (); // sort 7 candidates. erase (unique (candidates. begin (), candidates. end (), candidates. end (); // deduplication 8 DFS (candidates, path, 0, target); 9 return allpath; 10} 11 12 Void DFS (vector <int> & candidates, vector <int> & Path, int K, int target) {13 if (k> = candidates. size () | target <0) return; // If the element has been searched, or the first element has exceeded the target, 14 if (target = 0) is invalid) {// indicates that the addition of elements in the path is equal to the target, which is a valid solution of 15 allpath. push_back (PATH); 16 return; 17} 18 path. push_back (candidates [k]); 19 DFS (candidates, path, K, target-candidates [k]); // Adding k elements is one of the 20 path solutions. pop_back (); 21 DFS (candidates, path, k + 1, target); // do not specify k elements 22} 23 24 private: 25 vector <int> allpath; // record all solutions 26 };
Combination sum I & ii