Simple explanation and simple code C++
Intuition\n Describe your first thoughts on how to solve this problem. \nSince naive solution gives TLE, think of interchanging the way we keep the unique value
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince naive solution gives TLE, think of interchanging the way we keep the unique values and unique rows. Meaning go over values one by one and to maintain unique rows store the already used rows using some data structure.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort all the cells in the grid by their values and keep track of their original positions.\nTry dynamic programming with the following states: the current cell that we might select and a bitmask representing all the rows from which we have already selected a cell so far.\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    int f(int valIndex, int usedRowsMask,vector<vector<int>> &values,vector<vector<int>> &dp)\n    {\n        if(valIndex == values.size())   return 0;\n        if(dp[valIndex][usedRowsMask]!=-1)  return dp[valIndex][usedRowsMask];\n        \n        int sum = 0;\n        int row = values[valIndex][1];\n        if((1<<row)&usedRowsMask)\n            sum=f(valIndex+1,usedRowsMask,values,dp);\n        else\n        {\n            int j=valIndex;\n            while (j<values.size() && values[valIndex][0]==values[j][0])    j++;\n            \n            sum=max(f(valIndex+1,usedRowsMask,values,dp),\n                values[valIndex][0]+ f(j,(1<<row)|usedRowsMask,values,dp));\n        }\n            \n        return dp[valIndex][usedRowsMask]=sum;\n        \n    }\n    int maxScore(vector<vector<int>>& grid) {\n        int m=grid.size();\n        int n=grid[0].size();\n        vector<vector<int>> values;\n        for(int i=0;i<m;i++)\n        {\n            for(int j=0;j<n;j++)\n            {\n                values.push_back({grid[i][j], i, j});\n            }\n        }\n        sort(values.begin(), values.end());\n        vector<vector<int>> dp(m*n,vector<int>(pow(2,m+1),-1));\n        \n        return f(0,0,values,dp);\n    }\n};\n```
['C++']