2ms Solution for Combinations


  • 0
    B
    public List<List<Integer>> combine(int n, int k) {
    		List<List<Integer>> combs = new ArrayList<>();
    		int [] comb = new int[n+1];
    		Combine(combs , comb,0, 1, n, k);	
    		return combs;
    }
    
    private void Combine(List<List<Integer>> combs,int []comb,int size,int start,int n,int k){
    	if (k==0) {
    		List<Integer> list = new ArrayList<>();
    		for(int i=0;i<size;i++){
    			list.add(comb[i]);
    		}
    		combs.add(list);
    		return ;
    	}
    	for(int i=start;i<=n;i++){
    		comb[size++] = i;
    		Combine(combs, comb, size,i+1,n, k-1);
    		comb[size--] = i;
    	}
    }

Log in to reply
 

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