Backtracking solution


  • 0
    R

    This solution is inspired by Subset2 problem except here we check for the length of the list being added.

    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> each = new ArrayList<Integer>();
            handleList(res,each,n,k,1);
            return res;
        }
        public void handleList(List<List<Integer>> res, List<Integer> each,int n,int k,int start){
            if(each.size()==k){
                res.add(each);
                return;
            }
            for(int i=start;i<=n;i++){
                each.add(i);
                handleList(res, new ArrayList<>(each),n,k,i+1);
                each.remove(each.size()-1);
            }
            
        }
    }
    

Log in to reply
 

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