Easy JAVA recursive solution


  • 0
    T

    My easy java recursive solution.

    public class Solution {
    List<List<Integer>> mainList = new ArrayList<List<Integer>>();
    public List<List<Integer>> combine(int n, int k) {
        List<Integer> subList = new ArrayList<Integer>();
        generateCombinations(1, n, subList, k);
        return mainList;
    }
    
    public void generateCombinations(int startN, int endN, List<Integer> subList, int k){
        if(k==0){
            mainList.add(subList);
        }
        
        for(int j = startN; j<=endN;j++){
            List<Integer> subListtemp = new ArrayList<Integer>(subList);
            subListtemp.add(j);
            generateCombinations(j+1, endN, subListtemp, k-1);
        }
    } 
    }
    

    Cheers,


Log in to reply
 

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