Java Backtracking solution


  • 0
    M
        public List<List<Integer>> combine(int n, int k) {
        	List<List<Integer>> res = new ArrayList<>();
        	List<Integer> list = new ArrayList<>();
        	comb_recursion(n, k, 1, res, list);
        	return res;
        }
        
        private void comb_recursion(int n, int k, int start, List<List<Integer>> res, List<Integer> list){
            if(k==0) {
            	List<Integer> temp = new ArrayList<>(list);
            	res.add(temp);
            	return;
            }
            for(int i=start; i<=n; i++){
                list.add(i);
                comb_recursion(n, k-1, i+1, res, list);
                list.remove(list.size()-1);
            }
        }
    
    

Log in to reply
 

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