552. Student Attendance Record II

Problem:

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.

Solutions:

class Solution {
public:
    int checkRecord(int n) {
        vector<vector<int>> dp (2, vector<int>(6, 1));
        for (int i = 1; i <= n; ++i) {
            for (int a = 0; a < 2; ++a) {
                for (int l = 0; l < 3; ++l) {
                    int pos = getPosition(a, l);
                    // get P
                    dp[i & 0x1][pos] = dp[(i-1) & 0x1][getPosition(a, 2)]; 
                    // get A
                    if (a > 0) {
                        dp[i & 0x1][pos] = (dp[i & 0x1][pos] + dp[(i-1) & 0x1][getPosition(a - 1, 2)]) % MOD;
                    }
                    // get L
                    if (l > 0) {
                        dp[i & 0x1][pos] = (dp[i & 0x1][pos] + dp[(i-1) & 0x1][getPosition(a, l - 1)]) % MOD;
                    }

                }
            }
        }

        return dp[n & 0x1][getPosition(1, 2)];

    }

private:
    inline int getPosition(int absent, int late) {
        return absent * 3 + late;
    }

    static constexpr int MOD = 1000000007;

};

results matching ""

    No results matching ""