dfs就好了
先去重一下
class Solution { public: vector<vector<int> > ret; int cnt[55], n; void dfs(vector<int> candidates, int target, int k, vector<int> v) { if (target < 0) return; if(k == n) { if(target == 0) ret.push_back(v); return; } for(int i = 0; i <= cnt[candidates[k]]; i++) { if(i == 0) dfs(candidates, target, k + 1, v); else { for(int j = 1; j <= i; j++) v.push_back(candidates[k]); dfs(candidates, target - candidates[k] * i, k + 1, v); for(int j = 1; j <= i; j++) v.erase(v.end() - 1); } } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { memset(cnt, 0, sizeof(cnt)); vector<int> v; int length = candidates.size(); for(int i = 0; i < length; i++) cnt[candidates[i]]++; sort(candidates.begin(), candidates.end()); candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end()); n = candidates.size(); dfs(candidates, target, 0, v); return ret; } };