题目1:【二刷完成】
class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(n,k,1,0);
return ans;
}
public void backtracking(int targetSum, int k, int startIndex, int sum){
if (sum>targetSum){
return;
}
if (path.size()==k){
if (sum==targetSum){
ans.add(new ArrayList<>(path));
return;
}
}
for (int i=startIndex;i<=9-(k-path.size())+1;i++){
path.add(i);
sum += i;
backtracking(targetSum,k,i+1,sum);
path.removeLast();
sum -= i;
}
}
}
题目2:【二刷完成】
class Solution {
//存储结果
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits==null || digits.length()==0){
return list;
}
//初始对应所有的数字【包括0,1】,为了直接对应2-9,新增了两个无效的字符串""
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTracking(digits, numString, 0);
return list;
}
//每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild
StringBuilder temp = new StringBuilder();
public void backTracking(String digits, String[] numString, int num) {
//遍历全部一次记录一次得到的字符串
if (num == digits.length()) {
list.add(temp.toString());
return;
}
//str 表示当前num对应的字符串
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
//c
backTracking(digits, numString, num + 1);
//剔除末尾的继续尝试
temp.deleteCharAt(temp.length() - 1);
}
}
}