Approach
Depth-first search
For Number of Ways to Assign Edge Weights II, 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
- 83 lines of Java from the credited upstream file 3559.java.
- The implementation visibly relies on sequence storage.
- 7 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 int[] assignEdgeWeights(int[][] edges, int[][] queries) {3 final int n = edges.length + 1;4 int[] ans = new int[queries.length];5 final int[] depth = new int[n + 1];6 final int[][] parent = new int[LOG][n + 1];7 List<Integer>[] graph = new List[n + 1];8 Arrays.setAll(graph, i -> new ArrayList<>());9 10 for (int[] edge : edges) {11 final int u = edge[0];12 final int v = edge[1];13 graph[u].add(v);14 graph[v].add(u);15 }16 17 dfs(1, -1, graph, parent, depth);18 19 for (int k = 1; k < LOG; ++k)20 for (int v = 1; v <= n; ++v)21 if (parent[k - 1][v] != -1)22 parent[k][v] = parent[k - 1][parent[k - 1][v]];23 24 for (int i = 0; i < queries.length; ++i) {25 final int u = queries[i][0];26 final int v = queries[i][1];27 if (u == v) {28 ans[i] = 0;29 } else {30 final int a = lca(u, v, parent, depth);31 final int d = depth[u] + depth[v] - 2 * depth[a];32 ans[i] = modPow(2, d - 1);33 }34 }35 36 return ans;37 }38 39 private static final int MOD = 1_000_000_007;40 private static final int LOG = 17; 41 42 private void dfs(int u, int p, java.util.List<Integer>[] graph, int[][] parent, int[] depth) {43 parent[0][u] = p;44 for (int v : graph[u]) {45 if (v != p) {46 depth[v] = depth[u] + 1;47 dfs(v, u, graph, parent, depth);48 }49 }50 }51 52 private int lca(int u, int v, int[][] parent, int[] depth) {53 if (depth[u] < depth[v]) {54 final int temp = u;55 u = v;56 v = temp;57 }58 59 for (int k = LOG - 1; k >= 0; --k)60 if (parent[k][u] != -1 && depth[parent[k][u]] >= depth[v])61 u = parent[k][u];62 63 if (u == v)64 return u;65 66 for (int k = LOG - 1; k >= 0; --k)67 if (parent[k][u] != -1 && parent[k][u] != parent[k][v]) {68 u = parent[k][u];69 v = parent[k][v];70 }71 72 return parent[0][u];73 }74 75 private int modPow(long x, long n) {76 if (n == 0)77 return 1;78 if (n % 2 == 1)79 return (int) (x * modPow(x % MOD, (n - 1)) % MOD);80 return modPow(x * x % MOD, (n / 2)) % MOD;81 }82}83