[Google] LeetCode 2115 Find All Possible Recipes from Given Supplies
作者:互联网
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