Clean and Easy understanding Java Code with Backtracking


  • 0
    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> result = new ArrayList<>();
            List<Integer> solution = new ArrayList<>();
            helper(1, k, n, solution, result);
            return result;
        }
        
        private void helper(int start, int k, int sum, List<Integer> solution, List<List<Integer>> result) {
            if (k == 0 && sum == 0) {
                result.add(new ArrayList<Integer>(solution));
                return;
            }
            if (k < 0 || start > 9 || sum < 0) {// cut off invalid branches
                return;
            }
            for (int i = start; i <= 9; i++) {
                solution.add(i);
                helper(i + 1, k - 1, sum - i, solution, result);
                solution.remove(solution.size() - 1);
            }
        }
    }
    

Log in to reply
 

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