利用回溯算法解决组合求和问题 问题 思路 所有这类找出所有可行解的问题的都可以使用搜索回溯的方式解决。 回到本题,我们定义递归函数 dfs(target, combine, idx) 表示当前在 candidates 数组的第 idx 位,还剩 target 要组合,已经组合的列表为 combine。递归的终止条件为 target <= 0 或者 candidates 数组被全部用完。那么在当前的函数中,每次我们可以选择跳过不用第 idx 个数,即执行 dfs(target, combine, idx + 1)。也可以选择使用第 idx 个数,即执行 dfs(target - candidates[idx], combine, idx),注意到每个数字可以被无限制重复选取,因此搜索的下标仍为 idx。 更形象化地说,如果我们将整个搜索过程用一个树来表达,每次的搜索都会延伸出两个分叉,直到递归的终止条件,这样我们就能不重复且不遗漏地找到所有可行解。 JAVA代码 class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> ret = new ArrayList<>(); List<Integer> combin = new ArrayList<>(); dfs(candidates, target, ret, combin