#1916
Count Ways to Build Rooms in an Ant Colony
HardArrayMathDynamic ProgrammingTreeDepth-First SearchGraph TheoryTopological SortCombinatoricsDynamic ProgrammingTree TraversalDepth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to count the number of ways to build rooms based on their dependencies. It leverages the structure of the tree formed by the `prevRoom` array to efficiently compute the result.
⚙️
Algorithm
3 steps- 1Step 1: Build a tree structure from the `prevRoom` array to represent dependencies.
- 2Step 2: Use DFS to calculate the number of ways to build each subtree, storing results in a DP array.
- 3Step 3: Combine results from child nodes to compute the total number of valid build orders.
solution.py27 lines
1def countWays(prevRoom):
2 from collections import defaultdict
3 MOD = 10**9 + 7
4 n = len(prevRoom)
5 tree = defaultdict(list)
6 for i in range(1, n):
7 tree[prevRoom[i]].append(i)
8 dp = [0] * n
9 size = [0] * n
10
11 def dfs(node):
12 dp[node] = 1
13 size[node] = 1
14 for child in tree[node]:
15 dfs(child)
16 dp[node] = dp[node] * dp[child] % MOD
17 size[node] += size[child]
18 for child in tree[node]:
19 dp[node] = dp[node] * factorial(size[node] - 1) * pow(factorial(size[child]), MOD-2, MOD) % MOD
20 dfs(0)
21 return dp[0]
22
23def factorial(x):
24 res = 1
25 for i in range(2, x + 1):
26 res = res * i % (10**9 + 7)
27 return resℹ
Complexity note: The time complexity is O(n) due to the single DFS traversal of the tree structure, and the space complexity is O(n) for storing the tree and DP arrays.
- 1Understanding tree structures is crucial for solving dependency problems.
- 2Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.