题目描述:
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.
class Solution {
public:
int checkRecord(int n) {
// 先不考虑A,只用L和P组成长为i的字符串,那么可以在长为i-1的字符串结尾加上L或P
// 那么dp[i]=2*dp[i-1],但是加上L的时候要注意原来的字符串结尾不能为连续的两个L
// 即原字符串不能为[0:i-4]PLL,注意为了保证原字符串合法,LL之前一定是P
// 这是唯一一种可能导致加入L而不合法的情况,需要去除,所以dp[i]=2*dp[i-1]-dp[i-4]
if(n==1) return 3;
if(n==2) return 8;
long long mod=pow(10,9)+7;
vector<long long> dp(n+1,0);
dp[0]=1;
dp[1]=2;
dp[2]=4;
dp[3]=7;
for(int i=4;i<=n;i++)
{ // 因为dp中所有元素都已经取模,可能存在2*dp[i-1]<dp[i-4]
dp[i]=(2*dp[i-1]-dp[i-4]+mod)%mod;
}
// 现在考虑加上A,可以分为加上一个A或者不加A
long long result=0;
result+=dp[n];
for(int i=0;i<n;i++) // A左边有i个字符,右边有n-1-i个字符
{
result+=(dp[i]*dp[n-1-i])%mod;
result%=mod;
}
return result;
}
};