哎,,感觉好难啊,,,没有想到这么做用一个sum去加这样不会超时,如果先分块儿再用一个sum去存和的话,会超时,重复计算的太多了。。。
class Solution {
public:
int maxSideLength(vector<vector<int>>& mat, int threshold) {
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++) {
helper(mat, i, j, threshold);
}
}
return _max;
}
private:
void helper(vector<vector<int>>& mat, int row, int col, int threshold) {
int curRow = row;
int curCol = col;
int sum = 0;
while (curRow < mat.size() && curCol < mat[0].size()) {
// 添加新的列
for (int i = row; i <= curRow; i++) {
sum += mat[i][curCol];
if (sum > threshold) return;
}
// 添加新的行
for (int i = col; i < curCol; i++) {
sum += mat[curRow][i];
if (sum > threshold) return;
}
if (curRow - row + 1 > _max) _max = curRow - row + 1;
curRow++;
curCol++;
}
}
int _max = 0;
};