Day72力扣打卡

打卡记录

Day72力扣打卡_第1张图片


参加考试的最大学生数(压缩状态DP)

链接

class Solution:
    def maxStudents(self, seats: List[List[str]]) -> int:
        m, n = len(seats), len(seats[0])
        # a[i] 是第 i 排可用椅子的下标集合
        a = [sum((c == '.') << j for j, c in enumerate(s)) for s in seats]
        f = [[0] * (1 << n) for _ in range(m)]
        for j in range(1, 1 << n):
            lb = j & -j
            f[0][j] = f[0][j & ~(lb * 3)] + 1
        for i in range(1, m):
            j = a[i]
            while j:  # 枚举 a[i] 的子集 j
                f[i][j] = f[i - 1][a[i - 1]]  # 第 i 排空着
                s = j
                while s:  # 枚举 j 的子集 s
                    if (s & (s >> 1)) == 0:  # s 没有连续的 1
                        t = a[i - 1] & ~(s << 1 | s >> 1)  # 去掉不能坐人的位置
                        f[i][j] = max(f[i][j], f[i - 1][t] + f[0][s])
                    s = (s - 1) & j
                j = (j - 1) & a[i]
            f[i][0] = f[i - 1][a[i - 1]]
        return f[-1][a[-1]]

你可能感兴趣的:(从零开始的算法打灰,leetcode,python,算法)