Easy to understand backtracking approach


  • 0
    R
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new LinkedList<>();
        if(k > 9 || k < 1 || n > 45 || n < 1)   return res;
        List<Integer> list = new LinkedList<>();
        this.helper(k, n, 1, res, list);
        return res;
    }
    private void helper(int k, int n, int start, List<List<Integer>> res, List<Integer> list) {
        if(n == 0 && list.size() == k) {
            res.add(new LinkedList<>(list));
        }
        while(start < 10) {
            list.add(start);
            this.helper(k, n - start, ++start, res, list);
            list.remove(list.size() - 1);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.