文档讲解:216.组合总和III、17.电话号码的字母组合
题目链接:216.组合总和III、17.电话号码的字母组合
第一个题的思路和上一个做的组合题思路是一样的,组合题的模板一定要记住,套模板的时候要思路清晰。
第二题写的比较复杂了,首先将每一个按键都定义出来,然后每次递归回溯的时候记录的是当前按键是第几个,也就是第几层递归。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backTracking(k, n, 1, 0);
return res;
}
public void backTracking(int k, int n, int startNum, int sum){
if(sum>n || path.size()>k){
return;
}
if(path.size()==k){
if(sum == n){
// res.add(new ArrayList<>(path));
res.add(path);
return;
}
}
for(int i=startNum;i<=9; i++){
path.add(i);
sum+=i;
backTracking(k, n, i+1, sum);
sum-=i;
// path.removeLast();
path.remove(path.size()-1);
}
}
}
class Solution {
List<String> res = new ArrayList<>();
StringBuffer sb = new StringBuffer();
String[] num0 = new String[]{};
String[] num1 = new String[]{};
String[] num2 = new String[]{"a", "b", "c"};
String[] num3 = new String[]{"d", "e", "f"};
String[] num4 = new String[]{"g", "h", "i"};
String[] num5 = new String[]{"j", "k", "l"};
String[] num6 = new String[]{"m", "n", "o"};
String[] num7 = new String[]{"p", "q", "r", "s"};
String[] num8 = new String[]{"t", "u", "v"};
String[] num9 = new String[]{"w", "x", "y", "z"};
String[][] str = new String[][]{num0, num1, num2,num3, num4, num5, num6, num7, num8, num9};
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return res;
}
backtracking(digits, 0);
return res;
}
public void backtracking(String digits, int index){
if(sb.length()==digits.length()){
res.add(sb.toString());
return;
}
int num = Integer.parseInt(String.valueOf(digits.charAt(index)));
for(int i=0;i<str[num].length;i++){
sb.append(str[num][i]);
backtracking(digits, index+1);
sb.deleteCharAt(sb.length()-1);
}
}
}
更多【算法-代码随想录算法训练营第二十五天|216.组合总和III、17.电话号码的字母组合】相关视频教程:www.yxfzedu.com