Approach
Depth-first search
For Create Components With Same Value, 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
- 47 lines of C++ from the credited upstream file 2440.cpp.
- The implementation visibly relies on sequence storage.
- 3 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 int componentValue(vector<int>& nums, vector<vector<int>>& edges) {4 const int n = nums.size();5 const int sum = accumulate(nums.begin(), nums.end(), 0);6 vector<vector<int>> tree(n);7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 tree[u].push_back(v);12 tree[v].push_back(u);13 }14 15 for (int i = n; i > 1; --i)16 17 if (sum % i == 0 && dfs(nums, tree, 0, sum / i, vector<bool>(n)) == 0)18 return i - 1;19 20 return 0;21 }22 23 private:24 static constexpr int kMax = 1'000'000'000;25 26 27 28 int dfs(const vector<int>& nums, const vector<vector<int>>& tree, int u,29 int target, vector<bool>&& seen) {30 int sum = nums[u];31 seen[u] = true;32 33 for (const int v : tree[u]) {34 if (seen[v])35 continue;36 sum += dfs(nums, tree, v, target, std::move(seen));37 if (sum > target)38 return kMax;39 }40 41 42 if (sum == target)43 return 0;44 return sum;45 }46};47