Java recursive solution / 18ms


  • 0
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        result.add(new ArrayList<Integer>());
        if(n<k)
            return result;
        result = newCombine(1,n,k);
        return result;
    }
    public List<List<Integer>> newCombine(int start, int end, int k){
        List<List<Integer>> tempListArray = new ArrayList<List<Integer>>();
        if(end<start||k==0){
            tempListArray.add(new ArrayList<Integer>());
            return tempListArray;
        }
        for(int i=start;i<=(end-k+1);i++){
            for(List<Integer> list:newCombine(i+1,end,k-1)){
                List<Integer> tempList = new ArrayList<Integer>();
                tempList.add(i);
                tempList.addAll(list);
                tempListArray.add(tempList);
            }
        }
        return tempListArray;
    }

Log in to reply
 

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