day3:先序dfs传值与递归模拟

本质是运行栈

入栈:函数开始执行;

出栈:函数执行结束。

//拓扑排序版本
var fib = function(n) {
    if(n == 0) return 0
    if(n == 1) return 1
    const dp = new Array(n+1).fill(0)
    dp[1] = 1

    //入度统计
    const indeg = new Array(n+1).fill(2)
    indeg[0] = 0
    indeg[1] = 0

    //队列:队列中的状态点的值已经求出来了
    const begin = [0,1]

    const dfs = (x) => {
        //目标
        if(x === n) return

        //扩展
        const next = x === 0 ? [2] : [x+1,x+2] //next代表x的邻接节点
        for(let y of next){ 
            if(y > n) continue
            dp[y] += dp[x]  //y已经接收到x传来的值了
            indeg[y]--      //y所依赖的点的个数-1   
            if(indeg[y] === 0) dfs(y)  //y不依赖于任何点,y的值求出来了,可以入队
        }
    }

    for(let x of begin) dfs(x)

    return dp[n]
};

var fib = function(n) {
    if(n == 0) return 0
    if(n == 1) return 1
    const dp = new Array(n+1).fill(0)
    dp[1] = 1

    //入度:先序遍历要统计入度,入度的意义代表该点依赖于多少个点,当一个状态点接收到一个点的值,那么入度-1
    const indeg = new Array(n+1).fill(2)
    indeg[0] = 0
    indeg[1] = 0

    //队列:队列中的状态点的值已经求出来了
    const begin = [0,1]
    const dfs = (x) => {
        const stack = [[x,0]] //运行时栈
        while(stack.length){
            const [x,vis] = stack[stack.length-1] //vis用来标记访问过几个邻接节点

            //出栈条件:当邻接节点访问完毕的时候,可以出栈
            const case1 = x === 0 && vis === 1 //当x == 0时,需要访问的邻接节点的个数为1
            const case2 = x !== 0 && vis === 2 //当x != 0时,需要访问的邻接节点的个数为2
           
            //case1:扩展入栈 → 先序传值 
            if(!case1 && !case2){
                const next = x === 0 ? 2 : x + vis + 1 
                stack[stack.length-1][1]++ //代表扩展节点 + 1
                if(next > n) continue //next 
                indeg[next]--
                dp[next] += dp[x]
                if(indeg[next] === 0) stack.push([next,0]) 
            }
            
            //case2:结束出栈 → 后序传值 → 出栈后将该值传递给栈顶节点
            else stack.pop()
        }
    }
    for(let x of begin) dfs(x)
    return dp[n]
};

【【编译原理】哈工大公开课(高清版)】 https://www.bilibili.com/video/BV1dL4y1H7T8/?p=56&share_source=copy_web

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值