day25 打卡216.组合总和III 17.电话号码的字母组合
216.组合总和III
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backTracking(k, n, 1, 0);
return result;
}
private void backTracking(int k, int n, int startIndex, int sum) {
if (sum > n) return;
if (path.size() > k) return;
if (path.size() == k) {
if (sum == n) {
result.add(new LinkedList<>(path));
}
}
for (int i=startIndex; i<=9 ; i++) {
path.add(i);
sum += i;
backTracking(k, n, i+1, sum);
sum -= i;
path.removeLast();
}
}
}
17.电话号码的字母组合
class Solution {
//设置全局列表存储最后的结果
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) return list;
backTracking(digits, 0);
return list;
}
//每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild
StringBuilder sb = new StringBuilder();
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
private void backTracking(String digits, int index) {
if (index == digits.length()) {
list.add(sb.toString());
return;
}
Integer num = Integer.parseInt(digits.charAt(index)+"");
String str = numString[num];
for (int i = 0 ; i<str.length() ; i++) {
sb.append(str.charAt(i));
backTracking(digits, index+1);
sb.deleteCharAt(sb.length()-1);
}
}
}