Day2: BFS先序传值与递推|509,207,1857

入度表示依赖于多少个点。

1.扩展:把该点传给下一个点

a.拓扑排序;

b.判断环路;

c.递推公式;

d.队列类型;

普通队列;

优先队列;

双端队列

2.入队:

队列里面需要已知点。

出队的顺序就是拓扑排序的顺序。

1.状态:边界+目标;

2.递推;

3.顺序;

509

class Solution {
public:
    int fib(int n) {
        if(n == 0) return 0;
        if(n == 1) return 1;
        vector<int> dp(n+1, 0);
        dp[0] = 0;
        dp[1] = 1;
        vector<int> indeg(n+1, 2);
        indeg[0] = 0;
        indeg[1] = 0;
        queue<int> q;
        q.push(0);
        q.push(1);
        while(!q.empty()){
            int x = q.front();
            q.pop();
            if(x == n){
                return dp[x];
            }
            vector<int> next = x == 0 ? vector<int>{2} : vector<int>{x+1, x+2};
            for(int y : next){
                if(y > n) continue;
                dp[y] += dp[x];
                indeg[y]--;
                if(indeg[y] == 0) q.push(y);
            }
        }
        return 0;
    }
};

207

1.bfs先序

2.dfs先序

dfs先序栈模拟

class Solution {
public:
    vector<int> inProcess;
    vector<int> visit;
    bool cycle=false;
    vector<int> topo;
    void dfs(vector<vector<int>>& g, int now){
        if (cycle){
            return;
        }
        if (inProcess[now]){
            cycle = true;
            return;
        }
        if (visit[now]){
            return;
        }
        inProcess[now]=true;
        for(int next : g[now]){
            dfs(g,next);
        }
        inProcess[now]=false;
        visit[now] = true;
        topo.push_back(now);
    }
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        inProcess.resize(numCourses);
        visit.resize(numCourses);
        vector<vector<int>> g(numCourses);
        for(int i=0;i<prerequisites.size();i++){
            int a = prerequisites[i][0];
            int b = prerequisites[i][1];
            g[b].push_back(a);
        }
        //因为不知道
        for(int i=0;i<numCourses;i++){
            dfs(g,i);
        }
        if (cycle){
            return {};
        }else{
            reverse(topo.begin(), topo.end());
            return topo;
        }
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值