Java concise backtracking solution with comments


  • 0
    G

    public class CombinationSum {

    public List<List<Integer>> combinationSum3(int k, int n) {
    
        List<List<Integer>> ans = new ArrayList<>();
        backtrack(k, n, ans, new ArrayList<>(), 1);
        return ans;
    }
    
    public void backtrack(int k, int n, List<List<Integer>> ans, List<Integer> branch, int start) {
    
        if (k == 0 && n == 0) {
            ans.add(new ArrayList<>(branch));
            return;
        }
    
        for (int i = start; i <= 9; i++) {
            if (k > 0 && n >= i) {
                branch.add(i);
                // Continue to start from i + 1 to avoid duplication
                backtrack(k - 1, n - i, ans, branch, i + 1);
                // If we come to here, no valid result OR combination is done, backtrack the last element.
                branch.remove(branch.size() - 1);
            }
        }
    }
    

    }


Log in to reply
 

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