Approach
Depth-first search
For Maximize the Number of Target Nodes After Connecting Trees I, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 44 lines of C++ from the credited upstream file 3372.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> maxTargetNodes(vector<vector<int>>& edges1,4 vector<vector<int>>& edges2, int k) {5 vector<int> ans;6 const vector<vector<int>> graph1 = buildGraph(edges1);7 const vector<vector<int>> graph2 = buildGraph(edges2);8 int maxReachableInGraph2 = 0;9 10 if (k > 0)11 for (int i = 0; i < edges2.size() + 1; ++i)12 maxReachableInGraph2 =13 max(maxReachableInGraph2, dfs(graph2, i, -1, k - 1));14 15 for (int i = 0; i < edges1.size() + 1; ++i)16 ans.push_back(maxReachableInGraph2 + dfs(graph1, i, -1, k));17 18 return ans;19 }20 21 private:22 23 int dfs(const vector<vector<int>>& graph, int u, int prev, int k) {24 if (k == 0)25 return 1;26 int res = 0;27 for (const int v : graph[u])28 if (v != prev)29 res += dfs(graph, v, u, k - 1);30 return 1 + res;31 }32 33 vector<vector<int>> buildGraph(const vector<vector<int>>& edges) {34 vector<vector<int>> graph(edges.size() + 1);35 for (const vector<int>& edge : edges) {36 const int u = edge[0];37 const int v = edge[1];38 graph[u].push_back(v);39 graph[v].push_back(u);40 }41 return graph;42 }43};44