[Java] DFS + BitMask with comments O(N^2*2^N)
\nclass Solution {\n    int[][] dist;\n    public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n\t    //precalculate the distance of any two citi
```\nclass Solution {\n    int[][] dist;\n    public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n\t    //precalculate the distance of any two cities\n        dist = new int[n][n];\n        List<Integer>[] graph = new List[n];\n        for(int i=0; i<n; i++){\n            graph[i] = new ArrayList();\n        }\n        for(int[] e : edges){\n            graph[e[0]-1].add(e[1]-1);\n            graph[e[1]-1].add(e[0]-1);\n        }\n        for(int i=0; i<n; i++){\n            calcDist(graph, i, -1, i, 0);\n        }\n        int[] res = new int[n-1];\n        for(int i=1; i<(1<<n); i++){\n            int maxDist = 0;\n            int oneDistCount = 0;\n            int cities = 0;\n\t\t\t//find the max distance between each pair of cities\n            for(int j=0; j<n; j++){\n                if((i & (1<<j))!=0){\n                    cities++;\n                    for(int k=j+1; k<n; k++){\n                        if((i & (1<<k))!=0){\n                            maxDist = Math.max(maxDist, dist[j][k]);\n                            if(dist[j][k]==1){\n                                oneDistCount++;\n                            }\n                        }\n                    }                    \n                }\n            }\n\t\t\t//x cities form a substree if and only if there are x-1 edges among these cities\n            if(oneDistCount==cities-1 && maxDist>0) res[maxDist-1]++;\n        }\n        return res;\n    }\n    \n    public void calcDist(List<Integer>[] graph, int source, int prev, int cur, int d){\n        if(prev==cur){\n            return;\n        }\n        dist[source][cur] = d;\n        dist[cur][source] = d;\n        for(int next : graph[cur]) if(next!=prev){\n            calcDist(graph, source, cur, next, d+1);\n        }\n    }\n}\n```
[]