77. Combinations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> numList = new ArrayList<>();
dfs(resultList, numList, n, 1, k);
return resultList;
}

private void dfs(List<List<Integer>> resultList, List<Integer> numList, int n, int i, int k) {
if (numList.size() == k) {
resultList.add(new ArrayList<>(numList));
return;
}
if (n - i + 1 < k - numList.size()) { // 当可使用的数小于目标数时,剪枝
return;
}

// choose
numList.add(i);
dfs(resultList, numList, n, i + 1, k);
numList.remove(numList.size() - 1);

// not choose
dfs(resultList, numList, n, i + 1, k);
}
}

References

77. Combinations