一. 数可以选无穷多次
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(0,candidates,target,new ArrayList<>());
return res;
}
public void dfs(int index, int[] candidates,int target, ArrayList<Integer> list){
if(target==0){
res.add(new ArrayList<>(list));
return;
}
if(target<0) return;
for(int i=index;i<candidates.length;i++){
if(candidates[i]>target) return;
list.add(candidates[i]);
dfs(i,candidates,target-candidates[i],list);
list.remove(list.size()-1);
}
}
}
每个数可以选无穷多次
还有一种枚举方法是枚举一个数选多少次。这里回溯有点难理解
二. 数只能选一次
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
dfs(candidates,0,target);
return res;
}
void dfs(vector<int> &candidates, int index, int target){
if(target<0) return;
if(target==0){
res.push_back(path);
return;
}
for(int i=index;i<candidates.size();i++){
if(candidates[i]>target) break; // 剪短枝叶
if(i>index&&candidates[i]==candidates[i-1]) continue; // 去重
path.push_back(candidates[i]);
dfs(candidates,i+1,target-candidates[i]);
path.pop_back();
}
}
};
还有一种枚举方式枚举一个数选几次。