这道题在刘汝佳的书上是用网络流做的,但是数据量一大就会超时,使用贪心的思想来做就会非常简单
class Solution { public: vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) { int row = rowSum.size(); int col = colSum.size(); vector<vector<int>>ans; if (row == 0 || col == 0)return ans; ans = vector<vector<int>>(row, vector<int>(col, 0)); for (int i = 0; i < row + col; i++) { int tarRow = -1, tarCol = -1; int Min = 0x3f3f3f3f; for (int k = 0; k < row; k++) { if (rowSum[k] > 0 && rowSum[k] < Min) { Min = rowSum[k]; tarRow = k; } } Min = 0x3f3f3f3f; for (int k = 0; k < col; k++) { if (colSum[k] > 0 && colSum[k] < Min) { Min = colSum[k]; tarCol = k; } } if (tarRow == -1 ||tarCol == -1)break; Min = min(rowSum[tarRow], colSum[tarCol]); ans[tarRow][tarCol] = Min; rowSum[tarRow] -= Min; colSum[tarCol] -= Min; } return ans; } };