1.基于排列组合的DFS / 基于图的DFS
leetcode 39 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
dfs(res, list, candidates, target, 0);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int index){
// 设计DFS时,首先进行临界情况判断,判断何时DFS到底或者到临界情况
// 用index指导每波candidates遍历,遍历结束,return
if(index == candidates.length){
return;
}
// 满足结果需求,存储结果,return
if(target == 0){
res.add(new ArrayList<Integer>(list));
return;
}
// 开始深潜,使劲DFS,直到临界情况
dfs(res, list, candidates, target, index + 1);
// 进行判断,如果target - 候选人小于0, 指定不满足要求
// 如果大于等于0的话,继续进行判断or深潜
if(target - candidates[index] >= 0){
// 暂时将这个数加入list,后续继续进行判断
list.add(candidates[index]);
// 继续深潜,target值为target - candidates[index],看是否有其他数字加起来满足要求
dfs(res, list, candidates, target - candidates[index], index);
// 本轮DFS结束时,已对list进行处理,删除list中本轮的数字
list.remove(list.size() - 1);
}
}
}