Skip to content

Latest commit

 

History

History
26 lines (25 loc) · 720 Bytes

216. Combination Sum III.md

File metadata and controls

26 lines (25 loc) · 720 Bytes

Solution1

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(res, new ArrayList<>(), 1, 0, k, n);
        return res;
    }
    private void backtrack(List<List<Integer>> res, List<Integer> list, int num, int cnt, int k, int sum) {
        if (sum < 0) return;
        if (cnt == k && sum == 0) {
            res.add(new ArrayList(list));
            return;
        }
        for (int i = num; i <= 9; i++) {
            list.add(i);
            backtrack(res, list, i + 1, cnt + 1, k, sum - i);
            list.remove(list.size() - 1);
        }
    }
}

note

  • time O(n * n ^ 2) space O(n)
  • dfs