题目一:组合
题目描述:给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合
思路分析:见代码随想录
解法:回溯(优化)
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>(); // 收集路径
public List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return res;
}
/**
* 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex
* @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
*/
private void combineHelper(int n, int k, int startIndex) {
// 终止条件,找到大小为k的组合
if (path.size() == k) {
res.add(new LinkedList<>(path));
return;
}
// 单层搜索
// k - path.size() : 剩余要选取的元素
for (int i = startIndex; i <= n - (k - path.size()) + 1; i++) { // 确保了搜索范围在k个元素内
path.add(i);
combineHelper(n, k, i + 1); // 遍历剩下的元素
path.removeLast(); // 弹出元素
}
}
}