Approach
Depth-first search
For Number Of Ways To Reconstruct A Tree, 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
- 68 lines of Java from the credited upstream file 1719.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 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 checkWays(int[][] pairs) {3 final int MAX = 501;4 Map<Integer, List<Integer>> graph = new HashMap<>();5 int[] degrees = new int[MAX];6 boolean[][] connected = new boolean[MAX][MAX];7 8 for (int[] pair : pairs) {9 final int u = pair[0];10 final int v = pair[1];11 graph.putIfAbsent(u, new ArrayList<>());12 graph.putIfAbsent(v, new ArrayList<>());13 graph.get(u).add(v);14 graph.get(v).add(u);15 ++degrees[u];16 ++degrees[v];17 connected[u][v] = true;18 connected[v][u] = true;19 }20 21 22 for (final int u : graph.keySet())23 graph.get(u).sort(Comparator.comparingInt(a -> - degrees[a]));24 25 final int root = getRoot(degrees, graph.keySet().size());26 if (root == -1)27 return 0;28 if (!dfs(graph, root, degrees, connected, new ArrayList<>(), new boolean[MAX]))29 return 0;30 return hasMoreThanOneWay ? 2 : 1;31 }32 33 private boolean hasMoreThanOneWay = false;34 35 36 private int getRoot(int[] degrees, int n) {37 for (int i = 1; i < degrees.length; ++i)38 if (degrees[i] == n - 1)39 return i;40 return -1;41 }42 43 44 private boolean dfs(Map<Integer, List<Integer>> graph, int u, int[] degrees,45 boolean[][] connected, List<Integer> ancestors, boolean[] seen) {46 seen[u] = true;47 48 for (final int ancestor : ancestors)49 if (!connected[u][ancestor])50 return false;51 52 ancestors.add(u);53 54 for (final int v : graph.get(u)) {55 if (seen[v])56 continue;57 58 if (degrees[v] == degrees[u])59 hasMoreThanOneWay = true;60 if (!dfs(graph, v, degrees, connected, ancestors, seen))61 return false;62 }63 64 ancestors.remove(ancestors.size() - 1);65 return true;66 }67}68