DFS、BFS和Backtracking模板

灰太狼 2023-06-22 13:55 69阅读 0赞

DFS和Backtracking的区别

Backtracking是一种更通用的算法。

深度优先搜索是与搜索树结构相关的特定回溯形式。 来自维基百科:

一个从根开始(在图形情况下选择一个节点作为根)并在回溯之前尽可能地沿着每个分支进行探索。

它使用回溯作为其使用树的方法的一部分,但仅限于树结构。

但是,回溯可以用于任何类型的结构,其中可以消除域的部分 - 无论它是否是逻辑树。 Wiki示例使用棋盘和特定问题 - 您可以查看特定的移动,消除它,然后回溯到下一个可能的移动,消除它,等等。





























- DFS Backtracking
Target Structure Actual Tree/Graph Structure Any type of structure where portions of the domain can be eliminated (Chess Board, matrix, implicit tree)
Definition A specific form of backtracking related to searching tree/graph structures Traverse from the end and prune unacceptable cases
Start-At Point Root of the Tree End of the Goal
Moving Direction From the root to each branch From the end moving backwards

搜索问题的解法

  1. DFS(深度优先搜索)
  2. BFS(广度优先搜索)
  3. backtracking(回溯)

DFS模板

  1. void dfs(...)
  2. {
  3. // 结束递归的条件
  4. if (...) {
  5. ..... // 把“当前结果” 加入 “结果集容器” 中
  6. return;
  7. }
  8. // 继续递归,里面可能有回溯,也可能没有
  9. if (...) {
  10. ... // 在容器中保存当前数据
  11. dfs()
  12. ... // 在容器中删除上面保存的数据(注:这种情况下就称为回溯,很明显它是dfs的一个步骤)
  13. }
  14. }

难点

  1. 寻找dfs结束条件
  2. 继续dfs的条件

题目

78. Subsets
93. Restore IP Addresses

DFS(回溯)题型:

1) Leetcode 17. Letter Combinations of a Phone Number

Leetcode 22. Generate Parentheses

Leetcode 39. Combination Sum

Leetcode 40. Combination Sum II

Leetcode 46. Permutations

Leetcode 47. Permutations II

Leetcode 77. Combinations

Leetcode 78. Subsets

2)Leetcode 37. Sudoku Solver

BFS模板

模板1

  1. void bfs(...)
  2. {
  3. queue q;
  4. q.push(startRoot);
  5. while (!q.empty()) {
  6. // 按照节点处理
  7. curNode = q.front();
  8. q.pop();
  9. if (...) {
  10. // 处理curNode,并把curNode的相邻Nodes加入队列
  11. }
  12. }
  13. }

模板2

  1. void bfs(...)
  2. {
  3. queue q;
  4. q.push(startRoot);
  5. while (!q.empty()) {
  6. // 按照层次处理
  7. size = q.size();
  8. for (i = 0; i < size; i++) {
  9. curNode = q.front();
  10. q.pop();
  11. if (... ) {
  12. // 处理curNode,并把curNode的相邻Nodes加入队列
  13. }
  14. }
  15. }
  16. }

题目

199. Binary Tree Right Side View

参考

Restore IP Addresses

关于dfs、backtracking、recursion区别更多参考:

https://songhuiming.github.io/pages/2018/01/07/shen-du-sou-suo-hui-su-fa-he-di-gui/

发表评论

表情:
评论列表 (有 0 条评论,69人围观)

还没有评论,来说两句吧...

相关阅读

    相关 BackTrack5R3之连网

    打开BT5后,用ifconfig 命令查看网络接口信息,发现没有分配IP: ![Center][] 原因,主机,也就是物理机,停止了虚拟机的下面服务: ![Cen