C++ Memoization O(N*2^M)
O(N*2^M), where N = max(nums[i]), M = length(nums); N can be made equal to count(distinct(nums[i])).\n\n\nint d[17][1 << 16];\n\nclass Solution {\n    int searc
O(N*2^M), where N = max(nums[i]), M = length(nums); N can be made equal to count(distinct(nums[i])).\n\n```\nint d[17][1 << 16];\n\nclass Solution {\n    int search(vector<int>& a, int l, int m, int n, int i, int u, int x, int y)\n    {\n        int s = 0;\n        if (n == l)\n        {\n            s = a[i - 1] - u;\n            for (i = m = x = 0; i < a.size(); ++i)\n                if ((y & (1 << i)) == 0 && (x & (1 << a[i])) == 0)\n                    ++m, x |= 1 << a[i];\n            if (m == 0)\n                return s;\n            n = i = u = x = 0;\n        }\n        if (d[u][y] == 0)\n        {\n            int r = 1000;\n            for (; i < a.size() && l - n <= m; ++i)\n                if ((y & (1 << i)) == 0 && (x & (1 << a[i])) == 0)\n                    r = min(r, search(a, l, --m, n + 1, i + 1, n == 0 ? a[i] : u, x | (1 << a[i]), y | (1 << i)));\n            d[u][y] = r + 1;\n        }\n        return s + d[u][y] - 1;\n    }\n    \npublic:\n    int minimumIncompatibility(vector<int>& a, int k) {\n        memset(d, 0, sizeof(d));\n        sort(a.begin(), a.end());\n        int r = search(a, a.size() / k, a.size(), a.size() / k, 1, a[0], 0, 0);\n        return r == 1000 ? -1 : r;\n    }\n};\n```
[]