- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 49 lines of Python from the credited upstream file 2959.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 def numberOfSets(3 self,4 n: int,5 maxDistance: int,6 roads: list[list[int]],7 ) -> int:8 return sum(self._floydWarshall(n, maxDistance, roads, mask) <= maxDistance9 for mask in range(1 << n))10 11 def _floydWarshall(12 self,13 n: int,14 maxDistanceThreshold: int,15 roads: list[list[int]],16 mask: int,17 ) -> list[list[int]]:18 """19 Returns the maximum distance between any two branches, where the mask20 represents the selected branches.21 """22 maxDistance = 023 dist = [[maxDistanceThreshold + 1] * n for _ in range(n)]24 25 for i in range(n):26 if mask >> i & 1:27 dist[i][i] = 028 29 for u, v, w in roads:30 if mask >> u & 1 and mask >> v & 1:31 dist[u][v] = min(dist[u][v], w)32 dist[v][u] = min(dist[v][u], w)33 34 for k in range(n):35 if mask >> k & 1:36 for i in range(n):37 if mask >> i & 1:38 for j in range(n):39 if mask >> j & 1:40 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])41 42 for i in range(n):43 if mask >> i & 1:44 for j in range(i + 1, n):45 if mask >> j & 1:46 maxDistance = max(maxDistance, dist[i][j])47 48 return maxDistance49