C++ bitmask + DFS, with explanation.
Intuition\n Describe your first thoughts on how to solve this problem. \xA0\n \n# Approach\n Describe your approach to solving the problem. \n    As n is small,
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\xA0\n \n# Approach\n<!-- Describe your approach to solving the problem. -->\n    As n is small, find all possible subsets and see if any of them  can form a subtree. \n    If it can form a subtree, find the greatest distance while treating any node in that subset as the root node.\n    Once we visit a node, we clear the specific bit in the subtree, and after finishing dfs.\n    if subtree == 0, that means it is a valid subtree.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n    2^n for every subset and n for traversing that subset.\n    so tc would be = O(n * 2 ^ n) solution\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n    int dfs(int u,int par,vector<vector<int>> &adj,int &mask,int &ans){\n\n              if(!(mask & (1<<u)))return 0; // if the current node is not present in the subset.\n\n              mask = mask ^ (1<<u);\n\n              int fmax = 0 , smax = 0;\n\n              for(auto &v : adj[u]){\n                  if(v == par)continue;\n\n                  int val = dfs(v,u,adj,mask,ans);\n\n                  if(val >= fmax){\n                      smax = fmax;\n                      fmax = val;\n                  }\n                  else if(val > smax){\n                      smax = val;\n                  }\n              }\n\n         ans = max(ans,fmax+smax); // calculating the maximum distance at each node.\n\n         return fmax + 1;\n    }\n\n    vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n\n             vector<vector<int>> adj(n+1);\n\n             for(auto &it : edges){\n                 int u = it[0] , v = it[1];\n                 adj[u].push_back(v);\n                 adj[v].push_back(u);\n             }\n\n             unordered_map<int,int> mp;\n        \n            for(int bit=1;bit<(1<<n);bit++){\n\n                int mask = 0 , node = -1;\n                \n                for(int k=0;k<n;k++){\n                     if(bit & (1<<k)){\n                         mask |= (1<<(k+1));\n                         node = k+1;\n                     }\n                }\n\n                int ans = INT_MIN;\n\n                dfs(node,-1,adj,mask,ans); // to determine whether or not our subset is connected, and to calculate the maximum distance\n                \n                if(mask == 0)mp[ans]++;\n            }\n\n            vector<int> ans;\n\n            for(int i=1;i<n;i++){\n                int val = mp[i];\n                ans.push_back(val);\n            }\n\n        return ans;\n    }\n};\n```
['Bit Manipulation', 'Depth-First Search', 'Bitmask', 'C++']