[leetcode] problem 552 – student attendance record ii

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 10^9 + 7.

A student attendance record is a string that only contains the following three characters:

  1. ‘A’ : Absent.
  2. ‘L’ : Late.
  3. ‘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

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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// dp[i - 1] * dp[n - i], 1 <= i <= n, with A : "...+A+..."
// dp[i] + sum{dp[i - 1] * dp[n - i]}
public int (int n) {
int mod = (int) Math.pow(10, 9) + 7;
long[] dp = new long[n+1];
dp[0] = 1;
dp[1] = 2;

if (n > 1)
dp[2] = 4;

// without A
for (int i = 3; i <= n; i++)
dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3]) % mod;

// with A
long result = dp[n];

for (int i = 1; i <= n; i++)
result = (dp[i - 1] * dp[n - i] + result) % mod;

return (int) result;
}