代码随想录刷题Day24 | 77. 组合
77. 组合
题目:
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
思路:
采用回溯算法,回溯算法三部曲如下:
- 回溯函数的返回值以及参数
- 回溯函数终止条件
- 单层搜索过程
在本题中,回溯的终止条件就是path的长度等于k,然后再去回溯下一个值。
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backTracking(n, k, 1);
return result;
}
public void backTracking(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);
backTracking(n, k, i + 1);
path.remove(path.size() - 1);
}
}
}