Java simple solution+a branch cutting strategy


  • 0
    D
    public List<List<Integer>> combine(int n, int k) {
    		List<List<Integer>> re = new ArrayList<List<Integer>>();
    		List<Integer> curlist = new ArrayList<Integer>();
    		backtrack(re, n, 0, k, curlist);
    		return re;
        }
    public void backtrack(List<List<Integer>> re, int n, int cur, int k, List<Integer> curlist){
    	if(k == 0){
    		re.add(new ArrayList<Integer>(curlist));
    	}
    	else{	
    		int limit = n;                    //branch cuttiing.
    		if(cur == 0){
    			limit = n-k+1;
    		}
    		for(int i = cur + 1 ; i <= limit ; i ++){
    			curlist.add(i);
    			backtrack(re, n, i, k - 1, curlist);
    			curlist.remove(curlist.size()-1);
    		}
    	}
    }

Log in to reply
 

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