文档讲解:代码随想录
视频讲解:带你学透回溯算法(理论篇)| 回溯法精讲!_哔哩哔哩_bilibili
状态:
class Solution {
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<>();
path = new ArrayList<>();
backtracking(1, n, k);
return res;
}
public void backtracking(int startIndex, int n, int k) {
if(path.size() == k) {
res.add(new ArrayList(path));
return;
}
for(int i = startIndex; i <= n; i++) {
path.add(i);
backtracking(i + 1, n, k);
path.remove(path.size() - 1);
}
}
}
// 剪枝
class Solution {
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<>();
path = new ArrayList<>();
backtracking(1, n, k);
return res;
}
public void backtracking(int startIndex, int n, int k) {
if(path.size() == k) {
res.add(new ArrayList(path));
return;
}
for(int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
path.add(i);
backtracking(i + 1, n, k);
path.remove(path.size() - 1);
}
}
}
class Solution {
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> combinationSum3(int k, int n) {
res = new ArrayList<>();
path = new ArrayList<>();
backtracking(k, n, 1);
return res;
}
public void backtracking(int k, int n, int startIndex) {
if(path.size() == k && n == 0) {
res.add(new ArrayList(path));
return;
}
if(path.size() == k)return;
if(n <= 0)return;
for(int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
path.add(i);
backtracking(k, n - i, i + 1);
path.remove(path.size() - 1);
}
}
}
class Solution {
String[] str = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res;
StringBuilder path;
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
path = new StringBuilder();
if(digits.equals(""))return res;
backtracking(0, digits);
return res;
}
public void backtracking(int startIndex, String digits) {
if(digits.length() == path.length()) {
res.add(new String(path));
return;
}
int index = digits.charAt(startIndex) - '0';
for(int i = 0; i < str[index].length(); i++) {
path.append(str[index].charAt(i));
backtracking(startIndex + 1, digits);
path.deleteCharAt(path.length() - 1);
}
}
}
心得:都可以套模板,不算太难