排序+DFS
与Combination Sum II(参见这篇文章)不同的地方在于,重复的数字可以使用多次,无所谓啦,反正代码几乎都一样。
代码:
1 vector<vector<int> > res; 2 3 void dfs(vector<int> &candidates, vector<int> ans, int pos, int left) { 4 if (left == 0) 5 res.push_back(ans); 6 7 for (int i = pos; i < candidates.size() && candidates[i] <= left; i++) 8 if (i == pos || candidates[i] > candidates[i - 1]) { 9 ans.push_back(candidates[i]); 10 dfs(candidates, ans, i, left - candidates[i]); 11 ans.pop_back(); 12 } 13 } 14 15 vector<vector<int> > combinationSum(vector<int> &candidates, int target) { 16 sort(candidates.begin(), candidates.end()); 17 dfs(candidates, vector<int>(), 0, target); 18 19 return res; 20 }