题目描述
blablabla
样例
blablabla
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
ranges::sort(candidates);
vector<vector<int>> ans;
vector<int> path;
function<void(int, int)> dfs = [&](int i, int left) {
if (left == 0) {
ans.push_back(path);
return;
}
if (i == candidates.size() || left < 0) {
return;
}
// 不选
dfs(i + 1, left);
// 选
path.push_back(candidates[i]);
dfs(i, left - candidates[i]);
path.pop_back();
};
dfs(0, target);
return ans;
}
};
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
枚举选择哪个
Java 代码
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(0, target, candidates, ans, path);
return ans;
}
private void dfs(int i, int left, int[] candidates, List<List<Integer>> ans, List<Integer> path) {
if (left == 0) {
// 找到一个合法组合
ans.add(new ArrayList<>(path));
return;
}
if (left < candidates[i]) {
return;
}
// 枚举选哪个
for (int j = i; j < candidates.length; j++) {
path.add(candidates[j]);
dfs(j, left - candidates[j], candidates, ans, path);
path.remove(path.size() - 1); // 恢复现场
}
}
}