回溯通常存在于递归的下面,是一种纯暴力搜索
-
核心就是搜索问题可以抽象为树结构
-
集合的大小就构成了树的宽度,递归的深度,都构成的树的深度。
-
递归就要有终止条件,所以必然是一颗高度有限的树(N叉树)。
lc 77看这个概述就非常容易写出来了,题目是
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
在做这道题的时候我出了bug,原因是在循环里我一直放的是一个变量。改了一个小时,和昨天的函数名写错有异曲同工之妙。专门写篇文章强调一下这一点,看清楚变量名字!
class Solution {
int end;
List<List<Integer>> res = new ArrayList<>();
List<Integer> lst = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
end = n;
getCombine(1, k);
return res;
}
void getCombine(int n, int k){
// k每次-1, k=0不行
if(lst.size() == k){
res.add(new ArrayList<Integer>(lst));
return;
}
for(int i = n; i <= end; i ++){
lst.add(i);
getCombine(i + 1, k);
lst.remove(lst.size() - 1);
}
}
}