We are in charge of designing a system to install packages. We are required to support the installation of a package and all of its dependent packages.
Here is an example of a package structure that we would need to install:
A depends on B, C
B depends on D, E, F
C depends on F
F depends on G
Define what a package looks like and code a solution to this problem.
class Package {// define what this looks like}
class Installer {// solution}
这道题考察的是“依赖包安装”系统设计,核心是把包之间的依赖关系建模成图结构,然后在安装目标包时,递归或用栈 / 队列先处理它的所有依赖,再安装当前包。由于示例中存在共享依赖(例如 F 被 B 和 C 同时依赖),实现时通常需要用 visited 集合避免重复安装,并防止循环依赖导致死递归。面试中可以重点说明 Package 类如何保存依赖列表,以及 Installer 如何进行 DFS 深度优先遍历、去重和安装顺序控制。