題目要求:
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.
Example 1:
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
這里的核心是怎么切換保證能得到最大的值淮悼?
我本來想著利用計(jì)數(shù)排序的思路咱筛,先令最后的列滿足最大全為1约谈,然后是倒數(shù)第二列撤逢,但有個(gè)問題就是,如果原本此列都是1的話碘裕,就要出現(xiàn)錯(cuò)誤更啄,因?yàn)橐懦隋e(cuò)誤還要家條件判斷诫给,程序會很復(fù)雜巷蚪,明顯不是正確解病毡。
因此看了解決方案,是利用貪婪算法的路子屁柏。
利用行切換啦膜,保證0列全為1,然后后面全部使用列切換淌喻,對后面每列僧家,0多就切換,保證數(shù)值局部最大似嗤,如果1多直接加啸臀。
其中還有一個(gè)點(diǎn)就是對于構(gòu)建類似二進(jìn)制轉(zhuǎn)為十進(jìn)制方法届宠,因?yàn)樵趈ava,執(zhí)行二進(jìn)制操作會自動轉(zhuǎn)為十進(jìn)制顯示烁落,所以就利用位移操作來實(shí)現(xiàn)二進(jìn)制指定位的填充。
class Solution {
public int matrixScore(int[][] A) {
int n = A.length;
int m = A[0].length;
int res=n*(1<<m-1);
//得到最高位填充指定位置得到的二進(jìn)制數(shù)字
for(int j=1;j<m;j++){
int cur=0;
for(int i=0;i<n;i++) cur+=A[i][j]==A[i][0]?1:0;
res+=Math.max(cur,n-cur)*(1<<m-1-j);
//同樣利用位移實(shí)現(xiàn)指定二進(jìn)制位的填充
}
return res;
}
}