题目链接/文章讲解:代码随想录
视频讲解:和组合问题有啥区别?回溯算法如何剪枝?| LeetCode:216.组合总和III_哔哩哔哩_bilibili
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backTracking(k, n, 1, 0);
return ans;
}
public void backTracking(int k, int n, int startIndex, int sum) {
if (sum > n) {
return;
}
if (list.size() == k && sum == n) {
ans.add(new ArrayList<>(list));
return;
}
for (int i = startIndex; i <= 9; i++) {
list.add(i);
backTracking(k, n, i + 1, sum + i);
list.removeLast();
}
}
}
题目链接/文章讲解:代码随想录
视频讲解:还得用回溯算法!| LeetCode:17.电话号码的字母组合_哔哩哔哩_bilibili
这道题特殊在是从两个集合中找,所以就没有startIndex了
class Solution {
List<String> ans = new ArrayList<>();
StringBuilder sb = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return ans;
}
String[] num = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTraking(digits, num, 0);
return ans;
}
public void backTraking(String digits, String num[], int index) {
if (index == digits.length()) {
ans.add(sb.toString());
return;
}
String str = num[digits.charAt(index) - '0'];
for (int i = 0; i < str.length(); i++) {
sb.append(str.charAt(i));
backTraking(digits, num, index + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}