[LeetCode 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.

 

分析

这道题是个很难的题目,想一想数字那么大,用搜索枚举什么的肯定都会超时。只能尝试去推到递推关系,然后用动态规划的方法去解。

由于A只有0、1两种可能,所以分别考虑A == 0和A==1的情况,将结果相加。

A == 0时,此时只有L和P的组合。L和P为了满足不超过两个连续的L,结尾的两个字符只有如下三种情况:LL, PL, XP。X代表L和P均可。分别使用a,b,c代表上述三种情况。

那么可以得到如下推到关系:

a[i] = b[i-1],b[i] = c[i-1], c[i] = a[i-1] + b[i-1] + c[i-1]

那么总的num[i] = a[i] + b[i] + c[i]

A==1时,此时A可以在[1, n]的任意一个位置,当A放在i位置时,对应的左右两边的可能数分别为num[i-1], num[n-i],那么A在i位置时的总数为num[i-1] * num[n-i]。

这道题最重要的还是要找到最终的递推关系,但是在找递推关系的时候,需要把A给拿掉考虑,不然的话递推关系就很难写。

Code

class Solution {
public:
    int checkRecord(int n) {
        // represent LL as end
        vector<long long> a(n+1, 0);
        // represent PL as end
        vector<long long> b(n+1, 0);
        // represent XP as end
        vector<long long> c(n+1, 0);
        // represent total number
        vector<long long> num(n+1, 0);
        

        if (n < 2)
            return 3;
        num[0] = 1;
        num[1] = 2;
        num[2] = 4;
        a[2] = 1;
        b[2] = 1;
        c[2] = 2;
        
        int result = 0;
        long long m = pow(10, 9) + 7;
        for (int i = 3; i <= n; i ++)
        {
            a[i] = b[i-1];
            b[i] = c[i-1];
            c[i] = (a[i-1] + b[i-1] + c[i-1]) % m;
            num[i] = (a[i] + b[i] + c[i]) % m;
        }
        result += num[n];
        for (int i = 1; i <= n; i ++)
        {
            result += (num[i-1] * num[n-i]) % m;
            result = result % m;
        }
        
        return result;
    }
};

运行效率

Runtime: 40 ms, faster than 78.63% of C++ online submissions for Student Attendance Record II.

Memory Usage: 78.3 MB, less than 25.09% of C++ online submissions forStudent Attendance Record II.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值