目录
LeetCode 216.组合总和II
文章讲解:代码随想录
视频讲解:和组合问题有啥区别?回溯算法如何剪枝?| LeetCode:216.组合总和III_哔哩哔哩_bilibili
力扣题目:力扣
代码如下(Java):
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;
}
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;
}
}
}
LeetCode 17.电话号码的字母组合
文章讲解:代码随想录
代码如下(Java):
class Solution {
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0) return list;
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTracking(digits, numString, 0);
return list;
}
StringBuilder temp = new StringBuilder();
public void backTracking(String digits, String[] numString, int num){
if(num == digits.length()){
list.add(temp.toString());
return;
}
String str = numString[digits.charAt(num) - '0'];
for(int i = 0; i < str.length(); i++){
temp.append(str.charAt(i));
backTracking(digits, numString, num + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}