39. 组合总和 - 力扣(LeetCode)
需要定义一个index变量用来记录访问数组的下标,每次递归进行传参,在搜索过程中,因为为了避免重复数据,而且允许一个元素的重复出现,传入index时传入当前遍历的i值即可
class Solution {List<List<Integer>> list;List<Integer> res;int target;int count;public List<List<Integer>> combinationSum(int[] candidates, int target) {this.target = target;list = new ArrayList<>();res = new ArrayList<>();count = 0;dfs(candidates,0);return list;}public void dfs(int[] candidates,int index) {if (count == target) {list.add(new ArrayList<>(res));return;}for (int i = index; i < candidates.length; i++) {if (count + candidates[i] <= target) {res.add(candidates[i]);count += candidates[i];dfs(candidates,i);//回溯count -= candidates[i];res.remove(res.size() - 1);}}}
}