[2018-10-21] [LeetCode-Week7] 861. Score After Flipping Matrix 貪心

https://leetcode.com/problems/score-after-flipping-matrix/description/


We have a two dimensional matrix A where each value is 0 or 1.

A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.

After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.

Return the highest possible score.


因?yàn)槎M(jìn)制數(shù)高位的 1 比 后面所有的位都為 1 加起來還要大,所以只需要優(yōu)先滿足高位即可。
對(duì)于最高位,直接使用行變換全部置為 1.
接下來對(duì)于后面的位,沒辦法使用行變換(因?yàn)榍懊娴奈灰呀?jīng)最優(yōu)化),所以使用列變化使得 1 盡可能多即可。


class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {
        int n = A.size();
        int m = A[0].size();
        for (int i = 0; i < n; i++) {
            if (!A[i][0]) {
                for (int j = 0; j < m; j++) {
                    A[i][j] = 1 - A[i][j];
                }
            }
        }
        
        int ans = n * (1 << m);
        for (int j = 1; j < m; j++) {
            int cnt = 0;
            for (int i = 0; i < n; i++) {
                if (A[i][j]) {
                    cnt++;
                }
            }
            ans += max(cnt, n-cnt) * (1 << (m-j));
        }
        
        return ans >> 1;
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容