回溯算法
回溯算法实际上也是暴力解法,只是解决了多层嵌套for循环的问题。
n相当于树的宽度,k相当于深度。
77.组合问题
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
注意:1.之后补充学习ArrayList和LinkedList的相关API以及转换方式。
2.剪枝操作。
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
combine1(n, k, 1);
return result;
}
public void combine1(int n, int k, int start){
if(path.size() == k){
result.add(new ArrayList(path));
return;
}
for(int i = start; i <= n - (k - path.size()) +1; i ++){
path.add(i);
combine1(n, k, i + 1);
path.removeLast();
}
}
}