Student Attendance Record II

Similar Problems:

- Student Attendance Record I
- CheatSheet: Leetcode For Code Interview
- CheatSheet: Common Code Problems & Follow-ups
- Tag: #dynamicprogramming, #inspiring

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:

Input: n = 2 Output: 8 Explanation: There are 8 records with length 2 will be regarded as rewardable: "PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL" Only "AA" won't be regarded as rewardable owing to more than one absent times.

Note: The value of n won’t exceed 100,000.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

## https://code.dennyzhang.com/student-attendance-record-ii ## Basic Ideas: dynamic programming ## ## ## Each step, we may choose one of below ## A: previous doesn't have A ## L: previous doesn't have consecutive L ## P: no matter what ## ## Valid cases: ## XXXXXP ## XXXXXL ## XXXXLL ## XXXXXA ## ## XAXXXP ## XAXXXL ## XAXXLL ## ## dp[i][j][k] ## dp[i][2][3] ## At item i, the count of A is j, the count of tailing L is i ## ## Compact dp[i][j][k] to dp[i][j] ## ## dp[i][0] = sum(dp[i-1][0:3]) # item i must be P ## dp[i][1] = dp[i-1][0] # item i must be L ## dp[i][2] = dp[i-1][1] # item i must be L ## dp[i][3] = sum(dp[i-1][0:3])+sum(dp[i-1][0:3]) # item i must be A or P ## dp[i][4] = dp[i-1][3] # item i must be L ## dp[i][5] = dp[i-1][4] # item i must be L ## ## return sum(dp[n]) ## Complexity: Time O(n), Space O(n) class Solution: def checkRecord(self, n: int) -> int: mod = 10**9+7 dp = [[0 for _ in range(6)] for _ in range(n+1)] dp[0][0] = 1 for i in range(n): dp[i+1][0] = sum(dp[i][0:3])%mod dp[i+1][1] = dp[i][0] dp[i+1][2] = dp[i][1] dp[i+1][3] = sum(dp[i])%mod dp[i+1][4] = dp[i][3] dp[i+1][5] = dp[i][4] return sum(dp[n])%mod