Simple standard java solution with backtracking


  • 0
    C
    public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            helper(1, n, k, new ArrayList<Integer>(), result);
            return result;
        }
        private void helper(int start ,int n, int k, ArrayList<Integer> curr, List<List<Integer>> result){
            if(curr.size() == k) result.add(new ArrayList<Integer>(curr));
            else{
                for(int i=start;i<=n;i++){
                    curr.add(i);
                    helper(i+1, n, k, curr, result);
                    curr.remove(curr.size()-1);
                }
            }
        }
    

Log in to reply
 

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