Golang + Tree Diameter (Double BFS) + Bitmask
Approach\nUse bitmask to generate every city subset and then use double BFS to find tree diameter (max distance) for this city subset. Then increment the counte
# Approach\nUse bitmask to generate every city subset and then use double BFS to find tree diameter (max distance) for this city subset. Then increment the counter within the res slice. Basically combine Bitmasking to store state + Tree diameter (max distance)\n\n# Complexity\n- Time complexity:\nO(n * (2 ^ n))\n\n- Space complexity:\nO(n ^ 2) (Adjacency list)\n\n# Code\n```\nfunc countSubgraphsForEachDiameter(n int, edges [][]int) []int {\n    adj := make([][]int, n)\n    for _, edge := range edges {\n        u := edge[0] - 1\n        v := edge[1] - 1\n        adj[u] = append(adj[u], v)\n        adj[v] = append(adj[v], u)\n    }\n\n    res := make([]int, n - 1)\n\n    var maxDistance func(mask int) int\n    maxDistance = func(mask int) int {\n        start := -1\n        citiesInSubset := make(map[int]bool)\n        for src := 0; src < n; src++ {\n            if mask & (1 << src) == 0 {\n                continue\n            }\n            start = src\n            citiesInSubset[src] = true\n        }\n        if start == -1 {\n            return -1\n        }\n\n        var bfs func(start int) (int, int, bool)\n        bfs = func(start int) (int, int, bool) {\n            visited := make(map[int]bool)\n            var q []int\n            q = append(q, start)\n            visited[start] = true\n            farthestNode := -1\n            farthestDist := 0\n            for len(q) != 0 {\n                qSize := len(q)\n                for i := 0; i < qSize; i++ {\n                    u := q[0]\n                    farthestNode = u\n                    q = q[1:]\n                    if adj[u] == nil {\n                        continue\n                    }\n                    for _, v := range adj[u] {\n                        if _, ok := citiesInSubset[v]; !ok {\n                            continue\n                        }\n                        if _, ok := visited[v]; ok {\n                            continue\n                        }\n                        visited[v] = true\n                        q = append(q, v)\n                    }\n                }\n                farthestDist++\n            }\n            isValid := len(visited) == len(citiesInSubset)\n            return farthestNode, farthestDist - 1, isValid\n        }\n\n        // Tree diameter using BFS\n        farthestNode, _, isValid := bfs(start)\n        if !isValid {\n            return -1\n        }\n\n        _, treeDiam, _ := bfs(farthestNode)\n        return treeDiam\n    }\n\n    for mask := 0; mask < (1 << n); mask++ {\n        d := maxDistance(mask)\n        if d > 0 {\n            res[d - 1]++\n        }\n    }\n    return res\n}\n```
['Go']