Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
- new solution update 2022.02.07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& c, int target) {
sort(c.begin(), c.end());
vector<vector<int>> res;
vector<int> tmp;
dfs(res,tmp,c,target,0);
return res;
}
void dfs(vector<vector<int>>& res, vector<int>& tmp, vector<int>& c, int t, int i) {
if(!t) {
res.push_back(tmp);
return;
}
for(; i < c.size() and c[i] <= t; i++) {
tmp.push_back(c[i]);
dfs(res, tmp, c, t - c[i], i);
tmp.pop_back();
}
}
};
1 | class Solution { |