Share Java solution(5ms) using recursive


  • 0
    H

    public class Solution {

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        LinkedList<Integer> l = new LinkedList<Integer>();
        helper(1, n, k, res, l);
        return res;
    }
    public void helper(int start, int n, int k, List<List<Integer>> res, LinkedList<Integer> l){
        if(k==0){
            res.add(l);
            return;
        }
        for(int i=start;i<=n;i++){
            LinkedList<Integer> l2 = (LinkedList<Integer>)l.clone();
            l2.add(i);
            helper(i+1, n, k-1, res, l2);
        }
    }
    

    }


Log in to reply
 

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