递归-回溯2

namespace JD;
 

public class JDTest{
    public static void Show()
    {
        int[] arr = {1,2,3,4,5,6,7};
        var root = BuildTree2(arr,0,arr.Length-1);
        var stack = new Stack<int>();
        var rtList = new List<int>();
        Get21Method(root,rtList,root.val);
        foreach(var item in rtList) Console.WriteLine(item);

        IList<List<int>> rt = new List<List<int>>();
        FindPath(root, rt, stack);
        foreach (var item in rt) Console.WriteLine(string.Join("-", item));
        Console.WriteLine(11);
    }

    // 回溯法求完整路径是21的公约数的路径 不需要return;
    public static void Get21Method(TreeNode node,IList<int> rsList,int sum)
    {
        // if(node == null) return;
        if(node.left == null && node.right == null && sum == 15)
        {
            rsList.Add(node.val);
        }
        if(node.left != null) Get21Method(node.left,rsList,sum+node.left.val);
        if(node.right != null) Get21Method(node.right,rsList,sum+node.right.val);
    }

    public static void FindPath(TreeNode node, IList<List<int>> rsList, Stack<int> stack)
    {
        stack.Push(node.val);
        if (node.left == null && node.right == null && 21 % node.val == 0)
        {
            rsList.Add(stack.Reverse().ToList());
        }
        if (node.left != null) FindPath(node.left, rsList, stack);
        if (node.right != null) FindPath(node.right, rsList, stack);
        stack.Pop();
    }

    public static TreeNode BuildTree2(int[] arr, int left, int right)
    {
        if (left > right) return null;
        int mid = left + (right - left) / 2;
        var root = new TreeNode(arr[mid]);
        root.left = BuildTree2(arr, left, mid - 1);
        root.right = BuildTree2(arr, mid + 1, right);
        return root;
    }
}

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
5
4-2-1
4-2-3
4-6-7

其实了解了递归序,对回溯就有了很好的理解。

posted @ 2023-04-08 22:39  vba是最好的语言  阅读(28)  评论(0编辑  收藏  举报