程式語言 - LeetCode - C++ - 3546. Equal Sum Grid Partition I



參考資訊:
ChatGPT

題目:


方法:

1. 加總全部數值
2. 除以2就是要比對的數值
3. Row方向加總並且比對
4. Col方向加總並且比對

解答:

class Solution {
public:
    bool canPartitionGrid(vector<vector<int>>& grid) {
        using ll = long long;

        ll sum = 0;
        int row_size = grid.size();
        int col_size = grid[0].size();

        for (auto& row : grid) {
            for (int v : row) {
                sum += v;
            }
        }

        if (sum % 2) {
            return false;
        }

        ll v = 0;
        ll target = sum >> 1;

        for (int i = 0; i < row_size; ++i) {
            for (int j = 0; j < col_size; ++j) {
                v += grid[i][j];
                if (v == target) {
                    return true;
                }
            }
        }

        v = 0;
        for (int i = 0; i < col_size; ++i) {
            for (int j = 0; j < row_size; ++j) {
                v += grid[j][i];
                if (v == target) {
                    return true;
                }
            }
        }

        return false;
    }
};