classSolution{ // 用于存储所有可能的组合结果的列表 privatefinal List<List<Integer>> ans = new ArrayList<>(); // 用于存储当前路径的列表 privatefinal List<Integer> path = new ArrayList<>(); // 主要方法,寻找所有可以组成目标值 target 的组合 public List<List<Integer>> combinationSum(int[] candidates, int target) { // 开始深度优先搜索,初始状态为索引 0 和目标值 target dfs(0, target, candidates); return ans; }
// 深度优先搜索方法 publicvoiddfs(int i, int t, int[] candidates){ // 如果索引 i 到达数组末尾或目标值 t 小于 0,结束搜索 if (i == candidates.length || t < 0) { return; } // 如果目标值 t 等于 0,找到一个合法组合,将其添加到结果列表中 if (t == 0) { ans.add(new ArrayList<>(path)); return; }