ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Google] LeetCode 2115 Find All Possible Recipes from Given Supplies

2022-08-21 00:03:54  阅读:164  来源: 互联网

标签:Given Google string ingredients recipes recipe ele vector 2115


You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The \(i\)-th recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes.

You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them.

Return a list of all the recipes that you can create. You may return the answer in any order.

Note that two recipes may contain each other in their ingredients.

Solution

注意到 \(supplies\) 可以提供无限量的,所以另一个角度来看,这就意味着我们可以将其忽略,反正无限量供应。

所以接下来和拓扑排序一样,我们建边: \(ingredient \rightarrow recipe\),并统计 \(recipe\) 的度数。将度数为 \(0\) 加入到队列中,接下来就是拓扑排序的做法了。

点击查看代码
class Solution {
private:
    vector<string> ans;
    map<string, int> indeg;
    map<string, vector<string>> DAG;
    queue<string> q;
    
public:
    vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) {
        set<string> S;
        for(auto ele:supplies){
            S.insert(ele);
        }
        for(auto ele:recipes){
            indeg[ele]=0;
        }
        int n = ingredients.size();
        for(int i=0;i<n;i++){
            for(int j=0;j<ingredients[i].size();j++){
                if(S.find(ingredients[i][j])!=S.end())continue;
                DAG[ingredients[i][j]].push_back(recipes[i]);
                indeg[recipes[i]]+=1;
            }
        }
        for(auto ele:indeg){
            if(ele.second==0)
                q.push(ele.first);
        }
        while(!q.empty()){
            auto f = q.front(); q.pop();
            ans.push_back(f);
            for(auto ele: DAG[f]){
                indeg[ele]-=1;
                if(indeg[ele]==0)q.push(ele);
            }
        }
        return ans;
    }
};

标签:Given,Google,string,ingredients,recipes,recipe,ele,vector,2115
来源: https://www.cnblogs.com/xinyu04/p/16609099.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有