39. Combination Sum
为了避免前面选了 到后面选的时候 又选到了后面的前面 加一个position作为标记 循环从position开始
1 class Solution { 2 List<List<Integer>> res = new ArrayList<>(); 3 public List<List<Integer>> combinationSum(int[] candidates, int target) { 4 backtrack(candidates, target, 0, new ArrayList<>(), 0); 5 return res; 6 } 7 8 public void backtrack(int[] candidates, int target, int sum, List<Integer> list, int position) { 9 if(sum > target) return; 10 if(sum == target) { 11 res.add(new ArrayList<>(list)); 12 } 13 for(int i = position; i < candidates.length; i++) { 14 list.add(candidates[i]); 15 sum += candidates[i]; 16 backtrack(candidates, target, sum, list, i); 17 list.remove(list.size() - 1); 18 sum -= candidates[i]; 19 } 20 } 21 }