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.
思路:这个题看到了九章的答案精妙之处,良心网站。我搜了好多讲解都看不是特别懂,只有九章,一目了然。真心赞一个!
分情况讨论:因为A只出现一次,那么我们
without A的情况
dp[i] 表示,不包含A的长度为i的valid number. 由于尾巴只能是有P, L组合而成,那么尾巴valid的是: P, PL, PLL
dp[i] = dp[i-1] + dp[i-2] + dp[i - 3]
With A, 循环i,sum all of [0....i - 1] A [i + 1.....n] => dp[i-1] * dp[n - (i+ 1) + 1] => dp[i-1] * dp[n - i];
注意初始值init: dp[0] = 1
dp[1] = 2, P, L
dp[2] = 4, PL, LP, LL, PP
class Solution {
private static int MOD = 1000000007;
public int checkRecord(int n) {
if(n <= 0) {
return 0;
}
long[] dp = new long[n + 1];
// without A;
// end with P, PL, PLL.
// dp[i] 代表长度为i,不包含A的valid String 数目;
// dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
dp[0] = 1;
if(n >= 1) {
dp[1] = 2;
}
if(n >= 2) {
dp[2] = 4;
}
for(int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
dp[i] = dp[i] % MOD;
}
// with A;
// [0 ... i -1] A [i + 1... n];
long res = 0;
for(int i = 1; i <= n; i++) {
res += dp[i-1] * dp[n - i];
res = res % MOD;
}
return (int) (dp[n] + res) % MOD;
}
}