552 Student Attendance Record II
1. Question
Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after mod 109+ 7.
A student attendance record is a string that only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
A record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).
Example 1:
Note:The value of n won't exceed 100,000.
2. Implementation
(1) DP (数学推导)
思路: 我们定义T(n)为长度为n的rewardable records, T(n) = P(n) + L(n) + A(n)
P(n)是长度为n的以P结尾的record, P(n) = P(n - 1) + A(n - 1) + L(n - 1), P(1), P(2) = 3
L(n)是长度为n的以L结尾的record, L(n) = P(n - 1) + A(n - 1) + P(n - 2) + A(n - 2), L(1) = 1, L(2) = 3
A(n)是长度为n的以A结尾的record, noAP(n)是长度为n以P结尾且没有A的record, noAL(n)是长度为n以L结尾且没有A的record, A(n) = noAP(n - 1) + noAL(n - 1)
noAP(n) = noAP(n - 1) + noAL(n - 1), noAL(n) = noAP(n - 1) + noAP(n - 2), 通过观察可以得知noAP(n) = A(n), 将此代入noAL(n)的等式可以得出noAL(n) = A(n - 1) + A(n - 2)
将noAP(n) = A(n)和noAL(n) = A(n - 1) + A(n - 2)代入A(n) = noAP(n - 1) + noAL(n - 1),得出A(n) = A(n - 1) + A(n - 2) + A(n - 3), A(1) = 1, A(2) = 2, A(3) = 4
3. Time & Space Complexity
时间复杂度O(n), 空间复杂度O(n)
Last updated