Java easy to understand recursive solution.


  • 4
    C
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<Integer> nums = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            nums.add(i);
        }
        List<List<Integer>> ret = new ArrayList<>();
        dfs(nums, k, n, 0, new ArrayList<>(), ret);
        return ret;
    }
    
    private void dfs(List<Integer> nums, int k, int n, int idx, List<Integer> path, List<List<Integer>> ret) {
        if (k <= 0 && n <= 0) {
            if (k == 0 && n == 0) {
                ret.add(path);
            }
            return; // backtracking
        }
        for (int i = idx; i < nums.size(); i++) {
            List<Integer> p = new ArrayList<>(path);
            p.add(nums.get(i));
            dfs(nums, k-1, n-nums.get(i), i+1, p, ret);
        }
    }

Log in to reply
 

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