Example: Combinations - rFronteddu/general_wiki GitHub Wiki

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        // Given two integers n and k, return all possible combinations of k numbers 
        // chosen from the range [1, n].
        // You may return the answer in any order.
        List<List<Integer>> out = new LinkedList<>();
        List<Integer> comb = new LinkedList<>();
        add (out, comb, 1, n, k);
        return out;
    }
    
    void add (List<List<Integer>> out, List<Integer> comb, int start, int n, int k) {
        if (comb.size() == k) {
            // reached comb size
            out.add (new ArrayList<> (comb));
            return;
        }
        
        for (int i = start; i <= n; i++) {
            comb.add(i);
            add (out, comb, i + 1, n, k);
            // here we backtrack
            comb.remove (comb.size()-1);
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️