No.1
题目
组合
思路
递归分析
- 全局变量:存放符合条件单一结果的集合
path,存放符合条件结果的集合result
- 返回值:空,参数:
n、k、startIndex(记录递归搜索的起始位置)
- 终止条件:
path.size() == k,就存储结果,返回
- 单层递归逻辑:从
startIndex开始遍历,处理节点,递归,回溯
代码
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public void combineHelper(int n, int k, int start) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
// 横向遍历
for (int i = start; i <= n; i++) {
// 处理当前节点
path.add(i);
// 递归
combineHelper(n, k, i + 1);
path.removeLast();
}
}
public List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return result;
}