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 109 + 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 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.

DP求解,详细的分析见链接详细说明,程序如下所示:

class Solution {
    private final int MOD = 1000000007;
    public int checkRecord(int n) {
        if (n == 0){
            return 0;
        }
        if (n == 1){
            return 3;
        }
        if (n == 2){
            return 8;
        }
        int[] A = new int[n+1];
        A[0] = 1;
        A[1] = 1;
        A[2] = 2;
        int[] P = new int[n+1];
        P[1] = 1;
        P[2] = 3;
        int[] L = new int[n+1];
        L[1] = 1;
        L[2] = 3;
        for (int i = 3; i <= n; ++ i){
            A[i] = (((A[i-1] + A[i-2])%MOD) + A[i-3])%MOD;
            P[i] = (((A[i-1] + P[i-1])%MOD) + L[i-1])%MOD;
            L[i] = (((P[i-1] + A[i-1])%MOD) + ((P[i-2] + A[i-2])%MOD))%MOD;
        }
        return ((A[n] + L[n])%MOD + P[n])%MOD;
    }
}

猜你喜欢

转载自blog.csdn.net/excellentlizhensbfhw/article/details/81784136