Given two integers n _and _k, return all possible combinations of k _numbers out of 1 ..._n.

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if(n < 1 || k <= 0)
            return res;

        List<Integer> line = new ArrayList<>();

        helper(res, line, 1, n, k);

        return res;
    }

    public void helper(List<List<Integer>> res, List<Integer> line, int start, int n, int k) {
        if(line.size() == k) {
            res.add(new ArrayList<>(line));
            return;
        }

        for(int i = start; i <= n; i++) {
            line.add(i);
            helper(res, line, i + 1, n, k);
            line.remove(line.size() - 1);
        }
    }
}

results matching ""

    No results matching ""