Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public List<List<Integer>> combinationSum3(int k, int n) {
- List<List<Integer>> res = new ArrayList<>();
- backtracking(res, new ArrayList<Integer>(), 1, k, 0, n);
- return res;
- }
- private void backtracking(List<List<Integer>> res, List<Integer> path, int index, int k, int curr, int target) {
- if (path.size() == k) {
- if (curr == target) {
- res.add(new ArrayList<>(path));
- }
- return;
- }
- if (curr > target || path.size() > k) return;
- for (int i = index; i <= 9; i++) {
- path.add(i);
- backtracking(res, path, i + 1, k, curr + i, target);
- path.remove(path.size() - 1);
- }
- }
- }
Add Comment
Please, Sign In to add comment