77. Combinations

Question

Given a length k and a end number n, return all the combinations.

Algorithm

Use backtracking to find all the result. Start from 1 and adding and removing elements, each time the size of list is k, add to the result.

Code

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (n == 0 || k == 0) {
            return res;
        }
        helper(res, k, 1, n, new ArrayList<>());
        return res;
    }
    
    private void helper(List<List<Integer>> res, int k, int num, int n, List<Integer> list) {
        if (list.size() == k) {
            res.add(new ArrayList<>(list));
        }
        
        for (int i = num; i <= n; i++) {
            list.add(i);
            helper(res, k, i + 1, n, list);
            list.remove(list.size() - 1);
        }
    }
}