Simple java dfs solution


  • 0
    L
    private List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        if(k > 9) return new ArrayList<List<Integer>>();
        dfs(k,n,1,0,new ArrayList<>());
        return res;
    }
    
    private void dfs(int k,int n,int s,int depth,List<Integer> cur){
        if(depth == k && n == 0){
            res.add(new ArrayList<>(cur));
            return;
        }
        if(depth == k) return;
        for(int i = s; i <= 9; i++){
            cur.add(i);
            dfs(k,n-i,i+1,depth+1,cur);
            cur.remove(cur.size()-1);
        }
    }

Log in to reply
 

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