Simple java solution


  • -1
    H
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> each = new ArrayList<>();
        helper(res, each, 1, n, k);
        return res;
    }
    public void helper(List<List<Integer>> res, List<Integer> each, int pos, int n, int k) {
        if (each.size() == k) {
            res.add(each);
            return;
        }
        for (int i = pos; i <= n; i++) {
            each.add(i);
            helper(res, new ArrayList<>(each), i + 1, n, k);
            each.remove(each.size() - 1);
        }
        return;
    }

  • 0
    J

    why need to remove last one int each in phrase "each.remove(each.size() - 1); "?


  • 0
    H

    Because if you don't remove it, the prior value will keep at the end of the List each.
    For example, suppose pos = 0, n = 2. In for loop, if we have remove: when i = 0, each:<XX, 0> --> helper --> remove. then i = 1, each:<XX, 1> --> helper --> remove. then i = 2 each:<XX, 2> --> helper --> remove... If we don't have remove: when i = 0, each:<XX, 0> --> helper. then i = 1, each:<XX, 0, 1> --> helper. then i = 2 each:<XX,0,1, 2> --> helper...


Log in to reply
 

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