[LeetCode] DP之 Student Attendance Record II

来源:互联网 发布:网络访问控制技术应用 编辑:程序博客网 时间:2024/05/22 00:01

题目

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 10^9 + 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.

分析

这个题目其实有比较简单的解决方法,就是一个三维数组,但是很可惜的是超了内存。因此必须简化,但是这就需要大量的公式推导了,可以简化到只需要三个一维数组,但是推导过程比较复杂。
首先考虑三个数组,P[n]是以’p’结尾,长度为n。A[n]是以’p’结尾,长度为n。同理L[n]是以’l’结尾,长度为n。
因此,Total[n] = P[n] + A[n] + L[n]

  • 首先考虑P[n],这个没有什么限制,如果最后一位是’P’那么无需考虑n-1位的内容,所以其实就是P[n] = Total[n-1] = P[n-1] + A[n-1] + L[n-1], 另外,P[1] = 1
  • 然后是L[n],这个稍微复杂一些,需要n>=3的情况下才行。当n-1位是p或a时,没有什么问题。因此要考虑n-1是l且n-2也是l时,此时是不行的。因此L[n] = P[n-1] + A[n-1] + P[n-2] + A[n-2] (n>=3)
  • 最后是A[n],这个非常复杂,这需要不能出现多于一次A,此处就考虑两个数组noAP[n]和noAL[n],他们分别意味着,结尾是’P’的,且中间未出现过A的,以及结尾是’L’的,中间未出现‘A’的rewardable的个数。其中,noAP[n] = noAP[n-1] + noAL[n-1] (n >= 2),noAL[n] = noAP[n-1] + noAP[n-2] (n >= 2)
    A[n] = noAP[n-1] + noAL[n-1], (n >= 2)
    根据推导,可以得到 A[n] = A[n-1] + A[n-2] + A[n-3] (n >= 4)
    最后,在带入total的公式,得到最后的值即可

时间复杂度分析

时间复杂度是O(n),因为只需要遍历一次

代码

class Solution {public:    int checkRecord(int n) {        vector<int> p(n+1, 1), l(n+1,1), a(n+1,1);        const int  mod = 1000000007;        a[2] = 2;        a[3] = 4;        l[2] = 3;        for (int i = 2; i <= n; i++) {            p[i] = ((p[i-1] + a[i-1]) % mod + l[i-1]) % mod;            if (i >= 3) l[i] = ((a[i-1] + p[i-1]) % mod + (a[i-2] + p[i-2]) % mod) % mod;            if (i >= 4) a[i] = ((a[i-1]+ a[i-2]) % mod + a[i-3]) % mod;        }        return ((a[n] + p[n]) % mod + l[n]) % mod;    }};
阅读全文
0 0
原创粉丝点击