代码随想录训练营二刷第二十五天 | 216.组合总和III 17.电话号码的字母组合
一、216.组合总和III
题目链接:https://leetcode.cn/problems/combination-sum-iii/
思路:模板题
java
class Solution {
List<List<Integer>> arrayList = new ArrayList<>();
List<Integer> list = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
backTracking(k, n, 1);
return arrayList;
}
void backTracking(int k, int n, int index) {
if (list.size() < k && sum > n) return;
if (list.size() == k && sum == n) {
arrayList.add(new ArrayList<>(list));
return;
}
for (int i = index; i <= 9; i++) {
list.add(i);
sum += i;
backTracking(k, n, i+1);
list.remove(list.size()-1);
sum -= i;
}
}
}
二、17.电话号码的字母组合
题目链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
思路:每次递归选取的集合需要改变
java
class Solution {
List<String> list = new ArrayList<>();
StringBuilder builder = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits.length() == 0) return list;
String[] init = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
String[] strList = new String[digits.length()];
for (int i = 0; i < digits.length(); i++) {
strList[i] = init[digits.charAt(i) - '0'];
}
backTracking(strList, 0);
return list;
}
void backTracking(String[] strList, int index) {
if (builder.length() == strList.length) {
list.add(builder.toString());
return;
}
String strings = strList[index];
for (int i = 0; i < strings.length(); i++) {
builder.append(strings.charAt(i));
backTracking(strList, index + 1);
builder.deleteCharAt(index);
}
}
}