题目描述
没仔细看 perhaps call it面向数据编程?
算法1
(DFS) $O(n)$
blablabla
C++ 代码
class ThroneInheritance {
unordered_map<string, bool> dead; // Just to keep track of alive people
unordered_map<string, vector<string>> family;
string root;
public:
ThroneInheritance(string kingName) {
root = kingName;
}
void birth(string parentName, string childName) {
family[parentName].push_back(childName); // Appending at the end takes care of oldest to yongest
}
void death(string name) {
dead[name] = true;
}
void dfs(vector<string> &ans, string root) {
if (!dead[root]) { // Just check if dead before inserting into the order.
ans.push_back(root);
}
for (string child: family[root]) {
dfs(ans, child);
}
}
vector<string> getInheritanceOrder() {
vector<string> ans;
dfs(ans, root);
return ans;
}
};
/**
* Your ThroneInheritance object will be instantiated and called as such:
* ThroneInheritance* obj = new ThroneInheritance(kingName);
* obj->birth(parentName,childName);
* obj->death(name);
* vector<string> param_3 = obj->getInheritanceOrder();
*/
DFS 回溯Backtrace
Python3版
class ThroneInheritance:
def __init__(self, kingName: str):
self.nation = defaultdict(list)
self.king = kingName
self.dead = set()
def birth(self, parentName: str, childName: str) -> None:
self.nation[parentName].append(childName)
def death(self, name: str) -> None:
self.dead.add(name)
def getInheritanceOrder(self) -> List[str]:
self.ans = []
self.dfs(self.king)
return self.ans
def dfs(self, cur):
if cur not in self.dead:
self.ans.append(cur)
for child in self.nation[cur]:
self.dfs(child)