程式語言 - LeetCode - C++ - 3070. Count Submatrices with Top-Left Element and Sum Less Than k



參考資訊:
https://algo.monster/liteproblems/3070
https://algorithm.lomtom.cn/leetcode/count-submatrices-with-top-left-element-and-sum-less-than-k

題目:


方法:

Dynamic Programming

解答:

class Solution {
public:
    int countSubmatrices(vector<vector<int>>& grid, int k) {
        int r = 0;
        int row_size = grid.size();
        int col_size = grid[0].size();
        vector<vector<int>> sum(row_size + 1, vector<int>(col_size + 1, 0));

        for (int i = 1; i <= row_size; ++i) {
            for (int j = 1; j <= col_size; ++j) {
                sum[i][j] = sum[i - 1][j] + sum[i][j - 1];
                sum[i][j] -= sum[i - 1][j - 1];
                sum[i][j] += grid[i - 1][j - 1];

                if (sum[i][j] <= k) {
                    r += 1;
                }
            }
        }

        return r;
    }
};