backtrack_find_constrained_paths.cs[class]{backtrack_find_constrained_paths}-[func]{isSolution}
-
-[class]{backtrack_find_constrained_paths}-[func]{recordSolution}
-
-[class]{backtrack_find_constrained_paths}-[func]{isValid}
+backtrack_find_constrained_paths.cs/* 判断当前状态是否为解 */
+bool isSolution(List<TreeNode> state)
+{
+ return state.Count != 0 && state[^1].val == 7;
+}
-[class]{backtrack_find_constrained_paths}-[func]{makeChoice}
-
-[class]{backtrack_find_constrained_paths}-[func]{undoChoice}
-
-[class]{backtrack_find_constrained_paths}-[func]{backtrack}
+/* 记录解 */
+void recordSolution(List<TreeNode> state, List<List<TreeNode>> res)
+{
+ res.Add(new List<TreeNode>(state));
+}
+
+/* 判断在当前状态下,该选择是否合法 */
+bool isValid(List<TreeNode> state, TreeNode choice)
+{
+ return choice != null && choice.val != 3;
+}
+
+/* 更新状态 */
+void makeChoice(List<TreeNode> state, TreeNode choice)
+{
+ state.Add(choice);
+}
+
+/* 恢复状态 */
+void undoChoice(List<TreeNode> state, TreeNode choice)
+{
+ state.RemoveAt(state.Count - 1);
+}
+
+/* 回溯算法 */
+void backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> res)
+{
+ // 检查是否为解
+ if (isSolution(state))
+ {
+ // 记录解
+ recordSolution(state, res);
+ return;
+ }
+ // 遍历所有选择
+ foreach (TreeNode choice in choices)
+ {
+ // 剪枝:检查选择是否合法
+ if (isValid(state, choice))
+ {
+ // 尝试:做出选择,更新状态
+ makeChoice(state, choice);
+ List<TreeNode> nextChoices = new List<TreeNode>() { choice.left, choice.right };
+ backtrack(state, nextChoices, res);
+ // 回退:撤销选择,恢复到之前的状态
+ undoChoice(state, choice);
+ }
+ }
+}