JavaScript: All Subsets + DFS (diameter) solution
Reference: 1245. Tree Diameter\nProblem break-down:\n- Step1: build adjacent list\n- Step2: enumerate every possible subsets: bit-mask total = 2^n\n- Step3: ext
Reference: [1245. Tree Diameter](https://leetcode.com/problems/tree-diameter/)\nProblem break-down:\n- Step1: build adjacent list\n- Step2: enumerate every possible subsets: bit-mask `total = 2^n`\n- Step3: extract each sub-tree number\n- Step4: **isValid & isConnected** sub-tree and Run DFS\n\t- true: only when `visited nodes size === sub-tree size`\n\t- Attention: use a different Set() to memo this info, different from the Set() used in **backtracking** ( will be empty at the end)\n- Step5: after run twice DFS, find the maxDiameter for current sub-tree, update to result array, count + 1;\n\n\n```js\nvar countSubgraphsForEachDiameter = function(n, edges) {\n    function buildAdj(edges,n)\n    {\n        var adj = new Array(n).fill(0).map(el=>new Array(0));\n        for(var e of edges)\n        {\n            adj[e[0]-1].push(e[1]-1);\n            adj[e[1]-1].push(e[0]-1);\n        }\n        return adj;\n    }\n    function dfs(cur, dist, visited, nums)\n    {\n        nodes.add(cur);\n\n        if(visited.has(cur))\n        {\n            return;\n        }\n        if(maxDist<dist )\n        {\n            maxDist = dist;\n            farthest = cur;\n        }\n        visited.add(cur);\n        for(var next of adj[cur])\n        {   \n            if(nums.includes(next)) \n                dfs(next, dist+1, visited, nums);    \n        }\n        visited.delete(cur);\n    }\n    var res = new Array(n-1).fill(0);\n    // step1: build adj\n    var adj = buildAdj(edges,n);\n    \n    // step2: try 2^n possible subtrees\n    for(var state = 1; state< (1<<n); state++)\n    {\n        // 2.1 extract the subtree\n        var nums = [];\n        for(var i= 0; i<n;i++)\n        {\n            if( ((state>>i) & 1) === 1)\n            {\n                nums.push(i);\n            }\n                \n        }\n\n        if(nums.length<2)\n        {\n            continue;\n        }\n        \n        // 2.2 is connected and find the diameter\n        var visited = new Set();\n        var maxDist = -1;\n        var farthest = -1;\n        var nodes = new Set(); // traversed all nodes\n        dfs(nums[0],0, visited, nums);\n        if(nodes.size < nums.length)\n        {\n            // invalid tree: all visited size != nodes size\n            continue;\n        }\n        maxDist = 0;\n        visited.clear();\n        dfs(farthest,0,visited, nums);\n       \n        // 2.3.find max dist, add to result\n        if(maxDist>0)\n        {\n            res[maxDist-1]++;\n        }\n    }\n    return res;\n};\n```\n
[]