GuilinDev

Lc0077

05 August 2008

77 Combinations

题目

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

You may return the answer in any order.

Example 1:

1
2
3
4
5
6
7
8
9
10
Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Example 2:

1
2
Input: n = 1, k = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20
  • 1 <= k <= n

分析

利用数学归纳法的递归写法,和回溯模板。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> results = new ArrayList<>();
        combine(results, new ArrayList<Integer>(), n, k, 1);
        return results;
    }
    private void combine(List<List<Integer>> results, List<Integer> oneResult, int n, int k, int index) {
        if (k == 0) {
            results.add(new ArrayList<>(oneResult));
            return;
        }
        for (int i = index; i <= n; i++) {
            oneResult.add(i);
            combine(results, oneResult, n, k - 1, i + 1);
            oneResult.remove(oneResult.size() - 1);
        }
    }
}