LeetCode Problem 861

2018/12/2

861. Score After Flipping Matrix

問題描述

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

Note:

  • 1 <= A.length <= 20
  • 1 <= A[0].length <= 20
  • A[i][j] is 0 or 1.

問題分析

本題難度爲Medium!屬於貪心問題,已給出的函數定義爲

class Solution:
    def matrixScore(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """

本題的目的是矩陣各行表示的二進制數和最大,則要求最高位儘可能爲1,因此本題的思路爲首先改變每一行使得每一行的最高位爲1,然後遍歷所有非最高位的列,使得每一列的1的個數儘可能的多,這樣最終結果最大。

代碼實現

python3

# coding: utf-8
# coding: utf-8
class Solution:
    def matrixScore(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        temp_A = A.copy()
        row = len(temp_A)
        col = len(temp_A[0])
        def changeRow(A, n): # 改變A數組的第n行(0,1,...)
            for i in range(len(A[n])):
                A[n][i] = 1 if A[n][i] == 0 else 0
        def changeCol(A, n): # 改變A數組的第n列(0,1,...)
            for i in range(len(A)):
                A[i][n] = 1 if A[i][n] == 0 else 0
        
        # 所有最高位變爲1
        for i in range(row):
            if temp_A[i][0] != 1: 
                changeRow(temp_A, i)
        
        # 非最高位使每一列的1儘可能多
        for i in range(1,col):
            count_of_1 = 0
            for j in range(row):
                count_of_1 += temp_A[j][i]
            if count_of_1 < row/2:
                changeCol(temp_A, i)

        # 計算和
        res = 0
        for i in range(col):
            for j in range(row):
                res += temp_A[j][i] * (2**(col-1-i))

        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章