1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) { vector<vector<int>> g(n), ans(n); for (auto &e : edges) g[e[0]].emplace_back(e[1]); function<void(int, int)> dfs = [&](int f, int u) { for (int v : g[u]) { if (ans[v].empty() || ans[v].back() != f) { ans[v].emplace_back(f); dfs(f, v); } } }; for (int i = 0; i < n; ++i) dfs(i, i); return ans; } };
|