Add the chapter of backtracking. (#459)

This commit is contained in:
Yudong Jin
2023-04-16 04:52:42 +08:00
committed by GitHub
parent 8bc41bc013
commit 49606fd199
25 changed files with 897 additions and 9 deletions

View File

@@ -0,0 +1,75 @@
/**
* File: backtrack_find_constrained_paths.java
* Created Time: 2023-04-16
* Author: Krahets (krahets@163.com)
*/
import include.*;
import java.util.*;
public class backtrack_find_constrained_paths {
/* 判断当前状态是否为解 */
static boolean isSolution(List<TreeNode> state) {
return !state.isEmpty() && state.get(state.size() - 1).val == 7;
}
/* 记录解 */
static void recordSolution(List<TreeNode> state, List<List<TreeNode>> res) {
res.add(new ArrayList<>(state));
}
/* 判断在当前状态下,该选择是否合法 */
static boolean isValid(List<TreeNode> state, TreeNode choice) {
return choice != null && choice.val != 3;
}
/* 更新状态 */
static void makeChoice(List<TreeNode> state, TreeNode choice) {
state.add(choice);
}
/* 恢复状态 */
static void undoChoice(List<TreeNode> state, TreeNode choice) {
state.remove(state.size() - 1);
}
/* 回溯算法 */
static void backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> res) {
// 检查是否为解
if (isSolution(state)) {
// 记录解
recordSolution(state, res);
return;
}
// 遍历所有选择
for (TreeNode choice : choices) {
// 剪枝:检查选择是否合法
if (isValid(state, choice)) {
// 尝试:做出选择,更新状态
makeChoice(state, choice);
backtrack(state, Arrays.asList(choice.left, choice.right), res);
// 回退:撤销选择,恢复到之前的状态
undoChoice(state, choice);
}
}
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n初始化二叉树");
PrintUtil.printTree(root);
// 回溯算法
List<List<TreeNode>> res = new ArrayList<>();
backtrack(new ArrayList<>(), Arrays.asList(root), res);
System.out.println("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {
vals.add(node.val);
}
System.out.println(vals);
}
}
}

View File

@@ -0,0 +1,51 @@
/**
* File: preorder_find_constrained_paths.java
* Created Time: 2023-04-16
* Author: Krahets (krahets@163.com)
*/
import include.*;
import java.util.*;
public class preorder_find_constrained_paths {
static List<TreeNode> path;
static List<List<TreeNode>> res;
/* 前序遍历 */
static void preOrder(TreeNode root) {
// 剪枝
if (root == null || root.val == 3) {
return;
}
// 尝试
path.add(root);
if (root.val == 7) {
// 记录解
res.add(new ArrayList<>(path));
}
preOrder(root.left);
preOrder(root.right);
// 回退
path.remove(path.size() - 1);
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n初始化二叉树");
PrintUtil.printTree(root);
// 前序遍历
path = new ArrayList<>();
res = new ArrayList<>();
preOrder(root);
System.out.println("\n输出所有根节点到节点 7 的路径,且路径中不包含值为 3 的节点");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {
vals.add(node.val);
}
System.out.println(vals);
}
}
}

View File

@@ -0,0 +1,45 @@
/**
* File: preorder_find_nodes.java
* Created Time: 2023-04-16
* Author: Krahets (krahets@163.com)
*/
import include.*;
import java.util.*;
public class preorder_find_nodes {
static List<TreeNode> res;
/* 前序遍历 */
static void preOrder(TreeNode root) {
if (root == null) {
return;
}
// 尝试
if (root.val == 7) {
// 记录解
res.add(root);
}
preOrder(root.left);
preOrder(root.right);
// 回退
return;
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n初始化二叉树");
PrintUtil.printTree(root);
// 前序遍历
res = new ArrayList<>();
preOrder(root);
System.out.println("\n输出所有根节点到节点 7 的路径");
List<Integer> vals = new ArrayList<>();
for (TreeNode node : res) {
vals.add(node.val);
}
System.out.println(vals);
}
}

View File

@@ -0,0 +1,50 @@
/**
* File: preorder_find_paths.java
* Created Time: 2023-04-16
* Author: Krahets (krahets@163.com)
*/
import include.*;
import java.util.*;
public class preorder_find_paths {
static List<TreeNode> path;
static List<List<TreeNode>> res;
/* 前序遍历 */
static void preOrder(TreeNode root) {
if (root == null) {
return;
}
// 尝试
path.add(root);
if (root.val == 7) {
// 记录解
res.add(new ArrayList<>(path));
}
preOrder(root.left);
preOrder(root.right);
// 回退
path.remove(path.size() - 1);
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n初始化二叉树");
PrintUtil.printTree(root);
// 前序遍历
path = new ArrayList<>();
res = new ArrayList<>();
preOrder(root);
System.out.println("\n输出所有根节点到节点 7 的路径");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {
vals.add(node.val);
}
System.out.println(vals);
}
}
}

View File

@@ -0,0 +1,68 @@
"""
File: backtrack_find_constrained_path.py
Created Time: 2023-04-15
Author: Krahets (krahets@163.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import *
def is_solution(state: list[TreeNode]) -> bool:
"""判断当前状态是否为解"""
return state and state[-1].val == 7
def record_solution(state: list[TreeNode], res: list[list[TreeNode]]):
"""记录解"""
res.append(list(state))
def is_valid(state: list[TreeNode], choice: TreeNode) -> bool:
"""判断在当前状态下,该选择是否合法"""
return choice is not None and choice.val != 3
def make_choice(state: list[TreeNode], choice: TreeNode):
"""更新状态"""
state.append(choice)
def undo_choice(state: list[TreeNode], choice: TreeNode):
"""恢复状态"""
state.pop()
def backtrack(state: list[TreeNode], choices: list[TreeNode], res: list[list[TreeNode]]):
"""回溯算法"""
# 检查是否为解
if is_solution(state):
# 记录解
record_solution(state, res)
return
# 遍历所有选择
for choice in choices:
# 剪枝:检查选择是否合法
if is_valid(state, choice):
# 尝试:做出选择,更新状态
make_choice(state, choice)
backtrack(state, [choice.left, choice.right], res)
# 回退:撤销选择,恢复到之前的状态
undo_choice(state, choice)
"""Driver Code"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
print_tree(root)
# 回溯算法
res = []
backtrack(state=[], choices=[root], res=res)
print("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点")
for path in res:
print([node.val for node in path])

View File

@@ -0,0 +1,43 @@
"""
File: preorder_find_constrained_path.py
Created Time: 2023-04-15
Author: Krahets (krahets@163.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import *
def pre_order(root: TreeNode) -> None:
"""前序遍历"""
# 剪枝
if root is None or root.val == 3:
return
# 尝试
path.append(root)
if root.val == 7:
# 记录解
res.append(list(path))
pre_order(root.left)
pre_order(root.right)
# 回退
path.pop()
return
"""Driver Code"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
print_tree(root)
# 前序遍历
path = list[TreeNode]()
res = list[list[TreeNode]]()
pre_order(root)
print("\n输出所有根节点到节点 7 的路径,且路径中不包含值为 3 的节点")
for path in res:
print([node.val for node in path])

View File

@@ -0,0 +1,35 @@
"""
File: preorder_find_nodes.py
Created Time: 2023-04-15
Author: Krahets (krahets@163.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import *
def pre_order(root: TreeNode) -> None:
"""前序遍历"""
if root is None:
return
if root.val == 7:
# 记录解
res.append(root)
pre_order(root.left)
pre_order(root.right)
"""Driver Code"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
print_tree(root)
# 前序遍历
res = list[TreeNode]()
pre_order(root)
print("\n输出所有值为 7 的节点")
print([node.val for node in res])

View File

@@ -0,0 +1,42 @@
"""
File: preorder_find_paths.py
Created Time: 2023-04-15
Author: Krahets (krahets@163.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import *
def pre_order(root: TreeNode) -> None:
"""前序遍历"""
if root is None:
return
# 尝试
path.append(root)
if root.val == 7:
# 记录解
res.append(list(path))
pre_order(root.left)
pre_order(root.right)
# 回退
path.pop()
return
"""Driver Code"""
if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
print_tree(root)
# 前序遍历
path = list[TreeNode]()
res = list[list[TreeNode]]()
pre_order(root)
print("\n输出所有根节点到节点 7 的路径")
for path in res:
print([node.val for node in path])