代码随想录训练营 Day25
今日任务
216.组合总和Ⅲ
17.电话号码的字母组合
语言:Java
216. 组合总和Ⅲ
链接:https://leetcode.cn/problems/combination-sum-iii/
class Solution {
List<List<Integer>> result;
List<Integer> combination;
int curSum;
public void backTracking(int startNum, int k, int n){
if(curSum == n && combination.size() == k){
result.add(new ArrayList(combination));
return;
}
else if(combination.size() > k){
return;
}
for(int i = startNum; i <= 9 - (k - combination.size()) + 1; i++){
combination.add(i);
curSum += i;
if(curSum >= n && combination.size() < k){
combination.remove(combination.size() - 1);
curSum -= i;
continue;
}
backTracking(i + 1, k, n);
curSum -= combination.get(combination.size() - 1);
combination.remove(combination.size() - 1);
}
}
public List<List<Integer>> combinationSum3(int k, int n) {
result = new ArrayList<List<Integer>>();
combination = new ArrayList<Integer>();
curSum = 0;
backTracking(1, k, n);
return result;
}
}
17. 电话号码的字母组合
链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
class Solution {
List<String> result;
String path;
List<List<String>> map;
public void backTracking(String digits, int startIdx, int n){
if(path.length() == n){
result.add(path);
return;
}
for(int i = startIdx; i < n; i++){
char cur = digits.charAt(i);
for(int j = 0; j < map.get((int)cur - '2').size(); j++){
path += map.get((int)cur - '2').get(j);
backTracking(digits, i + 1, n);
path = path.substring(0, path.length() - 1);
}
}
}
public List<String> letterCombinations(String digits) {
result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
path = "";
map = new ArrayList<List<String>>();
//建立映射关系
int distance = 0;
for(int i = 2; i <= 9; i++){
List<String> temp = new ArrayList<String>();
if(i != 7 && i != 9){
for(int j = 0; j < 3; j++){
temp.add(String.valueOf(((char)('a' + distance))));
distance++;
}
map.add(new ArrayList(temp));
}
else{
for(int j = 0; j < 4; j++){
temp.add(String.valueOf(((char)('a' + distance))));
distance++;
}
map.add(new ArrayList(temp));
}
}
//回溯
backTracking(digits, 0, digits.length());
return result;
}
}