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. 

Idea: This question sees the subtleties of the answers in Chapter 9, Conscience Website. I searched for a lot of explanations, but I didn't understand them very much. Only nine chapters were clear at a glance. Really praise one!

Discuss by situation: Because A only appears once, then we

Without A

dp [i] means that the valid number of length i does not include A. Since the tail can only be a combination of P and L, the tail valid is: 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];

Note the initial value 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;
    }
}

 

 

Published 710 original articles · Like 13 · Visits 190,000+

Guess you like

Origin blog.csdn.net/u013325815/article/details/105525789