一、组合(LeetCode77)
回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtracing(n,k,1);
return res;
}
/**
* 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠index
* @param index 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
*/
void backtracing(int n,int k,int index){
if(path.size() == k){
res.add(new ArrayList<>(path));
return ;
}
for(int i = index;i <= n-(k-path.size())+1;i++){
path.add(i);
backtracing(n,k,i+1);
path.removeLast();
}
}
}
二、组合总和III(LeetCode216)
回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracing(n,k,0,1);
return res;
}
void backtracing(int targetsum, int k,int sum,int index){
if(sum > targetsum){
return;
}
if(path.size() == k){
if(sum == targetsum){
res.add(new ArrayList<>(path));
return;
}
}
for(int i = index;i <= 9-(k-path.size())+1;i++){
sum += i;
path.add(i);
backtracing(targetsum,k,sum,i+1);
sum -= i;
path.removeLast();
}
}
}
三、电话号码的字母组合(LeetCode17)
回溯
class Solution {
//设置全局列表存储最后的结果
List<String> res = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return res;
}
//初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串""
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
//迭代处理
backTracking(digits, numString, 0);
return res;
}
//每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild
StringBuilder s = new StringBuilder();
//比如digits如果为"23",num 为0,则str表示2对应的 abc
public void backTracking(String digits, String[] numString, int num) {
//遍历全部一次记录一次得到的字符串
if (num == digits.length()) {
res.add(s.toString());
return;
}
//str 表示当前num对应的字符串
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
s.append(str.charAt(i));
//c
backTracking(digits, numString, num + 1);
//剔除末尾的继续尝试
s.deleteCharAt(s.length() - 1);
}
}
}
1031

被折叠的 条评论
为什么被折叠?



