随想录训练营Day25 | 回溯 216.组合总和III, 17.电话号码的字母组合
标签: LeetCode闯关记
216.组合总和III
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
findCombination(k,n,1);
return res;
}
public void findCombination( int k, int targetSum,int startIndex ){
//剪枝
if(sum > targetSum){
return;
}
// 终止条件
if(path.size() == k){
if(sum == targetSum){//cfQ77,多了一个判断条件
res.add(new ArrayList<>(path));
return;
}
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
path.add(i);
sum += i;
findCombination(k,targetSum,i + 1);
sum -= i;
path.removeLast();
}
}
}
17. Letter Combinations of a Phone Number
class Solution {
List<String> res = new ArrayList<>();
StringBuilder temp = new StringBuilder();
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0){
return res;
}
String[] num_letter = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
findLetters(digits,num_letter,0);
return res;
}
public void findLetters(String digits, String[] num_letter, int index){
if(temp.length() == digits.length()){
res.add(temp.toString());
return;
}
String str = num_letter[digits.charAt(index) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
findLetters(digits,num_letter, index + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}