Title:
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C Where the candidate numbers sums to T.
The same repeated number is chosen from C unlimited number of times.
Note:
- All numbers (including target) would be positive integers.
- Elements in a combination (a1, a 2, ..., aK) must is in non-descending order. (ie, a1≤ a2≤ ... ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set and 2,3,6,7 target 7 ,
A Solution set is:
[7]
[2, 2, 3]
Idea: Basically the idea of Dfs. After sorting the array, each time you compare the current element to the target, it is possible to plug in a few current elements.
If the array has the same elements, it can be de-weighed with the commented out statement, or in the recursive function. No weight will not affect the result.
for (int i = (Target/candidates[idx]), I >= 0; i--) { record.push_back (Candidates[idx]);}
Used to calculate the maximum number of current elements to press into.
for (int i = (target/candidates[idx]); I >= 0; i--) { record.pop_back (); Searchans (ans, record, candidates, Target-i * Candidates[idx], idx + 1,candidates[idx]); Record.pop_back (); }
Pop up the stack, and then enter the recursive function. Note that it is possible that this element is not pressed in, so it is I >=0
ClassSolution {Public: vector<vector<int> > Combinationsum (vector<int> &candidates, intTarget) {//Start typing your/C + + solution below//do not write int main () function Sort (Candidates.begin (), Candidates.end ()); /*vector<int>::iterator pos = unique (Candidates.begin (), Candidates.end ()); Candidates.erase (POS, Candidates.end ()); */vector<vector<int> > ans; vector<int> record; Searchans (ans, record, candidates, tar Get, 0,-1); return ans;} Private: void Searchans (Vector<vector<int> > &ans, vector<int> &record, Vector<int > &candidates, int target, int idx, int prevalue) {if (target = = 0) {ans.push_back (record); return;} if (idx = = Candidates.size () | | candidates[idx] > Target | | prevalue = CANDIDATES[IDX]) {return;} for (in t i = (target/candidates[idx]); I >= 0; i--) {record.push_back (Candidates[idx]);} for (int i = (target/candidates[idx]); I >= 0; i--) {Record.po P_back (); Searchans (ans, record, candidates, Target-i * Candidates[idx], idx + 1, candidates[idx]);//record.pop_back (); } }};
Leetcode:combination Sum