77. 组合
回溯三部曲
1. 确定回溯函数的返回值和参数
本题中返回结果为一个List,回溯函数肯定不能返回List,返回值为void即可
参数为n和k
2. 确定递归中止条件
找到k个数字的集合就中止本次回溯
3. 确定单层递归操作
每层递归函数内,从当前位置向后遍历数字,将数字加入过程集合,进入下一层,之后回溯
class Solution {
List<Integer> item = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return res;
}
private void backtracking(int n, int k, int nowNum){
//确定递归中止条件
//if(nowNum > n){
// return;
//}
if(item.size() == k){
res.add(new ArrayList<>(item));
return;
}
for(int i = nowNum; i <= n - (k - item.size()) + 1; i++){
item.add(i);
backtracking(n, k, i + 1);
item.remove(item.size() - 1);
}
}
}
——————————————————————————————————————————
216. 组合总和 III
回溯三部曲
1.确定回溯函数返回值和参数
返回值为void,参数为k,n,和当前开始遍历的数字(1-9)
2.确定回溯终止条件
当相加的数字个数等于k时,中止此次回溯。
3.确定回溯单层过程
当找到相加之和为 n 的 k 个数时,将此次集合加到res中
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> item = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(k, n, 1);
return res;
}
private void backtracking(int k, int n, int startNum){
if(sum > n){
return;
}
if(item.size() == k){
if(sum == n){
res.add(new ArrayList<>(item));
}
return;
}
for (int i = startNum; i <= 9; i++) {
item.add(i);
sum += i;
backtracking(k, n, i + 1);
item.remove(item.size() - 1);
sum -= i;
}
}
}
——————————————————————————————————————————
17. 电话号码的字母组合
回溯三部曲
1.确定回溯函数返回值和参数
返回值为void,参数为输入字符串digits,以及当前要搜寻的数字位置
2.确定回溯终止条件
当当前组合字符串的长度等于digits长度时,将该组合加入返回集合
3.确定回溯单层过程
遍历当前数字的所有可用字母,加入组合字符串,回溯后减去当前字母
class Solution {
char[][] numChars = {
{'a','b','c'},
{'d','e','f'},
{'g','h','i'},
{'j','k','l'},
{'m','n','o'},
{'p','q','r','s'},
{'t','u','v'},
{'w','x','y','z'}
};
List<String> res = new ArrayList<>();
StringBuilder str = new StringBuilder();
public List<String> letterCombinations(String digits) {
backtracking(digits, 0);
return res;
}
private void backtracking(String digits, int index) {
if(str.length() == digits.length()){
if(str.length() > 0){
res.add(str.toString());
}
return;
}
char[] numChar = numChars[digits.charAt(index) - '2'];
for (char c : numChar) {
str.append(c);
backtracking(digits, index + 1);
str.deleteCharAt(str.length() - 1);
}
}
}