/** * @param num: Given the candidate numbers * @param target: Given the target number * @return: All the combinations that sum to target */ vector<vector<int>> combinationSum2(vector<int> &num, int target) { sort(num.begin(), num.end()); vector<vector<int>> ans; vector<int> v; combinationSum2Helper(num, target, 0, v, ans); return ans; }
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<vector<int>> res; vector<int> comb; combinationSum2Helper(candidates, target, res, comb, 0); return res; }
void combinationSum2Helper(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& comb, int begin) { if(target == 0) { res.push_back(comb); } for(int i = begin; i < candidates.size() && target >= candidates[i]; i++) { if(i > begin && candidates[i] == candidates[i-1]) { continue; } comb.push_back(candidates[i]); combinationSum2Helper(candidates, target - candidates[i], res, comb, i+1); comb.pop_back(); } }
void combinationSum2Helper(vector<int>& num, int gap, int begin, vector<int>& v,vector<vector<int>> &ans) { if (gap == 0) { ans.emplace_back(v); return; } for (size_t i = begin; i < num.size() && num[i] <= gap; ++i) { if ( i == begin || num[i] != num[i - 1]) { // Skip duplicates. // Each same element could be chosen only once // with the same previous nums. v.emplace_back(num[i]); combinationSum2Helper(num, gap - num[i], i + 1, v, ans); v.pop_back(); } } }
void backtarck(vector<vector<int> >res, vector<bool> flag,vector<int> tmp, vector<int> candidates,int target) { if(target == 0) { bool found = false; for(vector<vector<int> >::iterator it = res.begin(); it!= res.end();it++) { if(tmp == *it) { found = true; break; } } if(!found) res.push_back(tmp); return; } else if (target < 0) { return; }; int max = 0; for (int i = 0; i < tmp.size(); ++i) { if(tmp[i] > max) max = tmp[i] } for (int i = 0; i < candidates.size(); ++i) { if(!flag[i] && candidates[i] >= max) { flag[i] = true; tmp.push_back(candidates[i]); combinationSum2Helper(ans, flag, tmp, candidates, target - candidates[i]); tmp.pop_back(); flag[i] = false; } } }