1、什么是回溯法
回溯法也可以叫做回溯搜索法,它是一种搜索的方式。
回溯是递归的副产品,只要有递归就会有回溯。
2、题目
3、思路:
先弄清组合和排列的区别,类似高中数组概率学习的组合,其不区分顺序,比如12和21的组合是一样的,而排列区分顺序,如12和21不同
将其取数步骤用树结构表示如下图:
代码如下
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backTracking(n,k,1);
return res;
}
void backTracking(int n, int k, int startIndex) {
if(path.size()==k){
res.add(new ArrayList(path));//一定要注意,这里不能直接写path,浅拷贝和深拷贝的区别,此处若直接写path是浅拷贝,
return;
}
for(int i = startIndex;i<=n;i++){
path.add(i);
backTracking( n, k, i+1);
path.remove(path.size()-1);
}
}
}