3 ms easy understand solution


  • 2
    P
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> rst = new ArrayList<>();
        if(k <=0 || n < k){
            return rst;
        }
        
        helper(rst, new ArrayList<>(), n, k,1);
        return rst;
    }
    
    public void helper(List<List<Integer>> rst, List<Integer> path,  int n, int k, int pos){
        if(path.size() == k){
            rst.add(new ArrayList<>(path));
            return;
        }
        
        for(int i=pos; i<=n; i++){
            path.add(i);
            helper(rst, path, n, k,i+1);
            path.remove(path.size()-1);
        }
    }

Log in to reply
 

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