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