Java 1ms Solution, Easy Understand

  • 1

    this is a "subset" problem

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> rst = new ArrayList<>();
        if(n < k || k == 0){
            return rst;
        helper(rst, new ArrayList<>(), k,n,0,1);
        return rst;
    public void helper(List<List<Integer>> rst, List<Integer> path, int k, int n, int sum, int pos){
        if(sum == n && path.size() == k){
            rst.add(new ArrayList<>(path));
        for(int i= pos; i<=9; i++){
            if(sum + i > n) break;
            helper(rst, path, k, n, sum + i,i+1);

Log in to reply

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