leetcode552. Student Attendance Record II

来源:互联网 发布:视频播放插件video.js 编辑:程序博客网 时间:2024/06/06 13:11

leetcode552. 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 10^9 + 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动态规划的问题,刚开始做的时候也没有太多的头绪和思路,所以看了一下网上的,大多数都是用的三维数组来解决,但是我觉得太过复杂,而且难以理解。于是我从国外的网站上看到了一种一维数组的思想,于是再加上自己的理解。
首先,定义几个函数


Total(n): 字符长度为n的符合条件的个数

P(n): 字符长度为n的并且最后一位为P的符合条件的个数

L(n): 字符长度为n的并且最后一位为L的符合条件的个数

A(n):字符长度为n的并且最后一位为A的符合条件的个数

noAP(n):字符长度为n的并且没有一个A字符而且最后一位为P的符合条件的个数

noAL(n):字符长度为n的并且没有一个A字符而且最后一位为L的符合条件的个数


根据定义,可以得到
Total(n) = P(n) + L(n) + A(n); (n>=1)

P(n) = P(n-1) + L(n-1) + A(n-1); (n>=2)

然后由于规则规定不能有三个连续一起L字符,不然判定不符合条件,所以

L(n) = P(n-1) + A(n-1) + P(n-2) + A(n-2); (n>=3)

而且最多只能有一个A字符,因此

A(n) = noAP(n-1) + noAL(n-1); (n>=2)

同时,

noAP(n) = noAP(n-1) + noAL(n-1); (n>=2)

noAL(n) = noAP(n-1) + noAP(n-2); (n>=3)

由上面的关系式,然后我们再初始化一些条件,
P(1) = A(1) = L(1) = 1;
L(2) = 1;
noAL(1) = noAP(1) = 1;
noAL(2) = noAP(2) = 2;


以下是关于我的c++代码

class Solution {public:    int checkRecord(int n) {        if (n == 1) return 3;        int mod = 1000000007;        int* A = new int[n + 1];        int* L = new int[n + 1];        int* P = new int[n + 1];        int* noAL = new int[n + 1];        int* noAP = new int[n + 1];        //int A[10], L[10], P[10], noAL[10], noAP[10];        A[1] = L[1] = P[1] = 1;        L[2] = 3;        noAL[1] = noAP[1] = 1;        noAL[2] = noAP[2] = 2;        for (int i = 2; i <= n; i++) {            P[i] = ((P[i - 1] + A[i - 1])%mod + L[i - 1])%mod;            A[i] = (noAP[i - 1] + noAL[i - 1]) % mod;            noAP[i] = (noAP[i - 1] + noAL[i - 1]) % mod;            if (i >= 3) {                L[i] = ((P[i - 1] + A[i - 1]) % mod + (A[i - 2] + P[i - 2]) % mod) % mod;                noAL[i] = (noAP[i - 1] + noAP[i - 2]) % mod;            }        }        return ((A[n] + P[n]) % mod + L[n]) % mod;    }};
原创粉丝点击