Leetcode 77 Combinations (Backtracking)

Leetcode

问题描述

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

例子

Example:
Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

方法一

** Solution Java **
** 1ms, beats 100.00% **
** 42.6MB, beats 6.52% **
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();
        helper(1, n, k, ans, new ArrayList<Integer>());
        return ans;
    }
    private void helper(int start, int n, int k, List<List<Integer>> ans, List<Integer> cur) {
        if (k == 0) {
            ans.add(new ArrayList<Integer>(cur));
            return ;
        }
        for (int i = start; i <= n - k + 1; ++i) {
            cur.add(i);
            helper(i + 1, n, k - 1, ans, cur);
            cur.remove(cur.size() - 1);
        }
    }
}

方法二

** Solution Java **
** 3ms, beats 87.78% **
** 43.2MB, beats 6.52% **
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();
        if (k < 0 || n < k)
            return ans;
        if (k == 0) {
            ans.add(new ArrayList<Integer>());
            return ans;
        }
        ans = combine(n - 1, k - 1);
        for (List<Integer> list : ans) 
            list.add(n);
        ans.addAll(combine(n - 1, k));
        return ans;
    }
}
posted @ 2020-03-23 11:29  willwuss  阅读(98)  评论(0编辑  收藏  举报