216.组合总和III
题目链接
https://leetcode.cn/problems/combination-sum-iii/description/
题目描述
思路
自己写的效率会慢一些,而且没有用到剪枝
class Solution {
List<List<Integer>> list = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
trackback(k,n,1);
return list;
}
public void trackback(int k,int n,int startindex){
if(list1.size()==k){
int sum=0;
for (Integer integer : list1) {
sum+=integer;
}
if(sum==n){
list.add(new ArrayList<>(list1));
return;
}
}
for (int i = startindex; i <= 9; i++) {
list1.add(i);
trackback(k,n,i+1);
list1.remove(list1.size()-1);
}
}
}
参考答案
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backTracking(n, k, 1, 0);
return result;
}
private void backTracking(int targetSum, int k, int startIndex, int sum) {
// 减枝
if (sum > targetSum) {
return;
}
if (path.size() == k) {
if (sum == targetSum) result.add(new ArrayList<>(path));
return;
}
// 减枝 9 - (k - path.size()) + 1
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
path.add(i);
sum += i;
backTracking(targetSum, k, i + 1, sum);
//回溯
path.removeLast();
//回溯
sum -= i;
}
}
}
17.电话号码的字母组合
题目链接
https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/
题目描述
思路
class Solution {
StringBuilder stringBuilder = new StringBuilder();
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length()==0){
return list;
}
String[] nums = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
backTraing(digits,0,nums);
return list;
}
public void backTraing(String digits,int index,String[] nums){
//如果字符串是 “23”
//当index等于2的时候,也就是已经遍历完了2 和 3,终止
if(index==digits.length()){
list.add(stringBuilder.toString());
return;
}
//获取 2
int digit = digits.charAt(index) - '0';
//找到 2 对应的 "abc"
String letter = nums[digit];
for (int i = 0; i < letter.length(); i++) {
//遍历 abc 添加到结果集中
stringBuilder.append(letter.charAt(i));
//回溯,将index 加 1 就会遍历 3 的 "def"
backTraing(digits,index+1,nums);
将添加的删掉
stringBuilder.deleteCharAt(stringBuilder.length()-1);
}
}
}