问题描述:
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.
一般在讨论用动态规划解决字符串个数的问题中,总是利用字符串结尾来进行讨论,体现了字符串连续的特征。
分析:利用3个数组P[n],L[n],A[n]分别表示长度为n以P,L,A结尾的合法字符串,因此有:
1、在合法字符串后加上P还是合法字符串,P[n]=P[n-1]+L[n-1]+A[n-1];
2、加上L还是合法字符串的必然是以P结尾或者以A结尾的字符串或者倒数第二个字符不是L的合法字符串,即:L[n]=P[n-1]+A[n-1]+P[n-2]+A{n-2];
3、加上A还是合法字符串,只有P[n-1](不包含A)+L[n-1](不包含A),而有P[n-1](不包含A)=P[n-2](不包含A)+L[n-2](不包含A)=A[n-1],L[n-1](不包含A)=P[n-2](不包含A)+P[n-3](不包含A)=A[n-2]+A[n-3],综上,A[n]=A[n-1]+A[n-2]+A[n-3];
注意,前3项需要先求出来。
代码如下:
public int checkRecord(int n) {
if(n<=0)
return 0;
if(n==1)
return 3;
if(n==2)
return 8;
int mo=1000000007;
int[]P=new int[n+1];
int[]L=new int[n+1];
int[]A=new int[n+1];
P[1]=1;
L[1]=1;
A[1]=1;
P[2]=3;
L[2]=3;
A[2]=2;
P[3]=8;
L[3]=7;
A[3]=4;
for(int i=4;i<=n;i++){
P[i]=((P[i-1]+L[i-1])%mo+A[i-1])%mo;
L[i]=((P[i-1]+A[i-1])%mo+(P[i-2]+A[i-2])%mo)%mo;
A[i]=((A[i-1]+A[i-2])%mo+A[i-3])%mo;
}
return ((P[n]+L[n])%mo+A[n])%mo;
}