题目分类
77. Combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
题目解析:
- 求组合可以使用回溯
代码:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> combs = new ArrayList<>();
backtracking(n, k, 1, new ArrayList<>(), combs);
return combs;
}
public void backtracking(int n, int k, int idx, List<Integer> path, List<List<Integer>> combs) {
if (path.size() == k) {
combs.add(new ArrayList<>(path));
return;
}
for (int i = idx; i <= n; i++) {
path.add(i);
backtracking(n, k, i+1, path, combs);
path.remove(path.size() - 1);
}
}
}