题目列表
解题过程
1、216.组合总和III
找出所有相加之和为 n
**的 k
****个数的组合,且满足下列条件:
- 只使用数字1到9
- 每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
思路: 这题思路和 77.组合
一样,而且还可以剪枝。
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;
}
public void backTracking(int k, int n, int startIndex, int sum) {
//剪枝
if (sum > n) {
return;
}
if (path.size() == k) {
if (sum == n) {
result.add(new ArrayList<>(path));
return;
}
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
sum += i;
path.add(i);
backTracking(k, n, i + 1, sum);
sum -= i;
path.removeLast();
}
}
}
2、17.电话号码的字母组合
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
思路: 字母和数字的映射用一个map或者二维数组存储。
class Solution {
List<String> res = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return res;
}
backTracing(digits, 0);
return res;
}
StringBuilder temp = new StringBuilder();
//初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串""
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public void backTracing(String digits, int index) {
if (digits.length() == index) {
res.add(temp.toString());
return;
}
//str 表示当前index对应的字符串
String str = numString[digits.charAt(index) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracing(digits, index + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}
总结
回溯好像只有递归的写法,太好啦。