- 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 Java from the credited upstream file 2959.java.
- The implementation visibly relies on sequence storage.
- 8 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 public int numberOfSets(int n, int maxDistance, int[][] roads) {3 final int maxMask = 1 << n;4 int ans = 0;5 6 for (int mask = 0; mask < maxMask; ++mask)7 if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance)8 ++ans;9 10 return ans;11 }12 13 private int floydWarshall(int n, int maxDistanceThreshold, int[][] roads, int mask) {14 int maxDistance = 0;15 int[][] dist = new int[n][n];16 Arrays.stream(dist).forEach(A -> Arrays.fill(A, maxDistanceThreshold + 1));17 18 for (int i = 0; i < n; ++i)19 if ((mask >> i & 1) == 1)20 dist[i][i] = 0;21 22 for (int[] road : roads) {23 final int u = road[0];24 final int v = road[1];25 final int w = road[2];26 if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) {27 dist[u][v] = Math.min(dist[u][v], w);28 dist[v][u] = Math.min(dist[v][u], w);29 }30 }31 32 for (int k = 0; k < n; ++k)33 if ((mask >> k & 1) == 1)34 for (int i = 0; i < n; ++i)35 if ((mask >> i & 1) == 1)36 for (int j = 0; j < n; ++j)37 if ((mask >> j & 1) == 1)38 dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);39 40 for (int i = 0; i < n; ++i)41 if ((mask >> i & 1) == 1)42 for (int j = i + 1; j < n; ++j)43 if ((mask >> j & 1) == 1)44 maxDistance = Math.max(maxDistance, dist[i][j]);45 46 return maxDistance;47 }48}49