dfs bfs感觉也都不难 但还是不太会写 细节整不明白呜呜呜
感谢lc官解
![](https://img-blog.csdnimg.cn/6e53e8f6e4d04cf2b5047653eb89a416.png)
![](https://img-blog.csdnimg.cn/6a9bc12cfe3c400c91d4b7c9b383954b.png)
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
dfs(candidates, target, ans, list, 0);
return ans;
}
public void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> list, int flag){
if(flag == candidates.length) return;
if(target == 0){
ans.add( new ArrayList<Integer>(list));
return;
}
dfs(candidates, target, ans, list, flag + 1);
if(target - candidates[flag] >= 0){
list.add(candidates[flag]);
dfs(candidates, target - candidates[flag], ans, list, flag);
list.remove(list.size() - 1);
}
}
}
|