《LeetCode力扣练习》代码随想录——回溯算法(组合总和—Java)
刷题思路来源于 代码随想录
39. 组合总和
-
回溯
class Solution { private List<Integer> path = new ArrayList<>(); private List<List<Integer>> result = new ArrayList<>(); public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); backtrack(candidates, target, 0, 0); return result; } private void backtrack(int[] candidates, int target, int sum, int startIndex) { if (sum > target) { return; } if (sum == target) { result.add(new ArrayList<>(path)); return; } for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) { sum = sum + candidates[i]; path.add(candidates[i]); backtrack(candidates, target, sum, i); sum = sum - candidates[i]; path.remove(path.size() - 1); } return; } }