提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
本篇我们讲解了,什么是回溯算法,知道了回溯和递归是相辅相成的。 接着提到了回溯法的效率,回溯法其实就是暴力查找,并不是什么高效的算法。 然后列出了回溯法可以解决几类问题,可以看出每一类问题都不简单。 最后我们讲到回溯法解决的问题都可以抽象为树形结构(N叉树),并给出了回溯法的模板
一、力扣77. 组合
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
fun(n,k,1,1);
return res;
}
public void fun(int n, int k, int cur, int index){
if(cur > k){
res.add(new ArrayList<>(path));
return;
}
for(int i = index; i <= n; i ++){
path.add(i);
fun(n,k,cur+1,i+1);
path.remove(path.size()-1);
}
}
}
二、力扣216. 组合总和 III
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
fun(k,n,1,0);
return res;
}
public void fun(int k, int n, int index,int sum){
if(path.size() == k){
if(n == sum){
res.add(new ArrayList<>(path));
}
return;
}
for(int i = index; i < 10; i ++){
path.add(i);
fun(k,n,i+1,sum+i);
path.remove(path.size()-1);
}
}
}
三、力扣17. 电话号码的字母组合
class Solution {
List<String> res = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String[] str = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
if(digits.length() == 0){
return res;
}
fun(digits,0);
return res;
}
public void fun(String digits, int cur){
if(sb.length() >= digits.length()){
res.add(sb.toString());
return;
}
for(int i = 0; i < str[digits.charAt(cur)-'0'].length(); i ++){
sb.append(str[digits.charAt(cur)-'0'].charAt(i));
fun(digits,cur+1);
sb.deleteCharAt(sb.length()-1);
}
}
}
四、力扣39. 组合总和
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
fun(candidates,target,0,0);
return res;
}
public void fun(int[] candidates, int target,int index,int sum){
if(sum >= target){
if(sum == target){
res.add(new ArrayList<>(path));
}
return;
}
for(int i = index; i < candidates.length; i ++){
if(candidates[i] + sum > target){
return;
}
path.add(candidates[i]);
fun(candidates,target,i,sum+candidates[i]);
path.remove(path.size()-1);
}
}
}
本文详细介绍了回溯算法的概念,以及它在LeetCode编程题目的四个实例:77.组合、216.组合总和III、17.电话号码的字母组合和39.组合总和。通过这些例子展示了回溯算法如何解决具有树形结构的问题。
881

被折叠的 条评论
为什么被折叠?



