题目链接:https://leetcode.cn/problems/combinations/
方法一 回溯
1 方法思想
2 代码实现
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
collect(n, 1, k);
return result;
}
public void collect(int n, int start, int k){
if (path.size() >= k){
result.add(new ArrayList<>(path));
return;
}
for (int i = start; i <= n; i++) {
path.add(i);
collect(n, i + 1, k);
path.removeLast();
}
}
}
3 复杂度分析
时间复杂度:
空间复杂度: