组合总和
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(target,candidates,0,0);
return res;
}
public void dfs(int target,int[] candidates,int cur,int start){
if(cur > target ) return;
if(cur == target){
res.add(new ArrayList<>(list));
return;
}
for(int i=start;i<candidates.length;i++){//从start开始
list.add(candidates[i]);
dfs(target,candidates,cur+candidates[i],i);//这里是i不是i+1
list.remove(list.size()-1);
}
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(target,candidates,0,0);
return res;
}
public void dfs(int target,int[] candidates,int cur,int start){
if(cur > target) return;
if(cur == target){
res.add(new ArrayList(list));
return;
}
for(int i=start;i<candidates.length;i++){//从start开始
if(i!=start && candidates[i] == candidates[i-1]) continue;//去重
list.add(candidates[i]);
dfs(target,candidates,cur+candidates[i],i+1);//i+1不重复取
list.remove(list.size()-1);
}
}
}
不一样的烟火
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步