文章作者:Tyan 博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,根据变换规则可知,第一位和最后一位总是0
,因此只有中间6
位数在变,最大可能的变换周期为2^6
。因此只要记录变换周期,因此周期中的所有状态就可得出变换结果,使用字典stat
来判断每次变换是否与之前的重复,列表state
记录状态变化,当出现重复状态时,计算变换的周期peroid
,以及一个周期的状态变化,如果没出现周期,则直接返回变换后的结果,如果出现了,则返回计算后的状态。
- Version 1
class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
stat = {}
state = []
temp = ''.join(list(map(str, cells)))
stat[temp] = 0
count = 0
pre = cells[:]
state.append(pre)
for i in range(n):
count = 1
cells[0] = 0
cells[7] = 0
for j in range(1, 7):
if (pre[j-1] == 1 and pre[j 1] == 1) or (pre[j-1] == 0 and pre[j 1] == 0):
cells[j] = 1
else:
cells[j] = 0
temp = ''.join(list(map(str, cells)))
if temp not in stat:
stat[temp] = count
pre = cells[:]
state.append(pre)
else:
peroid = count - stat[temp]
state = state[stat[temp]:]
break
if count == n:
return cells
return state[(n - count) % peroid]
Reference
- https://leetcode.com/problems/prison-cells-after-n-days/