Simple Backtracking Java Solution


  • 0
    J

    '''
    public class Solution {

    List<List<Integer>> result;
    public List<List<Integer>> combine(int n, int k) {
        
        result= new ArrayList<List<Integer>>();
     //   if(k==0 || n<k) return result; 
        
        helper(n,k,1,new ArrayList<Integer>());
        
        return result;
    }
    

    public void helper(int n,int k,int start,List<Integer> curList){

       if(curList.size()==k){
           result.add(new ArrayList<Integer>(curList));
           return;
       } 
       
       for(int i=start;i<=n;i++){
           curList.add(i);
           helper(n,k,i+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.