77. 组合
- 学习文章链接:
- 思路:牢牢记住回溯三部曲,并在此基础上明白减枝操作,具体细节见代码注释。回溯是一种暴力解法,因此时间效率并不高。
- 代码:
class Solution {
List<List<Integer>> res;
LinkedList<Integer> path;
public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<>();
path = new LinkedList<>();
backtracking(n, k, 1);
return res;
}
public void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
path.add(i);
backtracking(n, k, i + 1);
path.removeLast();
}
}
}