题目如下:

解题思路:colsum[i] = 0 和 colsum[i] = 2的场景很简单,output[0][i] 和 output[1][i]  都为0或者都为1即可。剩下colsum[i] = 1的场景,优先把1分配给output[0][i] ,达到upper上限后,再把剩余的1分配给output[1][i]。

代码如下:

class Solution(object):
    def reconstructMatrix(self, upper, lower, colsum):
        """
        :type upper: int
        :type lower: int
        :type colsum: List[int]
        :rtype: List[List[int]]
        """
        res = [[0] * len(colsum) for _ in range(2)]
        one_count = 0
        two_count = 0
        for i in range(len(colsum)):
            if colsum[i] == 2:
                res[0][i] = res[1][i] = 1
                two_count += 1
            elif colsum[i] == 1:one_count += 1
        if upper < two_count or lower < two_count or (upper - two_count + lower - two_count) != one_count:
            return []

        count = upper - two_count
        for i in range(len(colsum)):
            if colsum[i] == 0 or colsum[i] == 2:continue
            if count > 0:
                res[0][i] = 1
                count -= 1
            else:
                res[1][i] = 1

        return res
01-10 13:52