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.

class Solution {
public:
    int checkRecord(int n) {
        // 先不考虑A,只用L和P组成长为i的字符串,那么可以在长为i-1的字符串结尾加上L或P
        // 那么dp[i]=2*dp[i-1],但是加上L的时候要注意原来的字符串结尾不能为连续的两个L
        // 即原字符串不能为[0:i-4]PLL,注意为了保证原字符串合法,LL之前一定是P
        // 这是唯一一种可能导致加入L而不合法的情况,需要去除,所以dp[i]=2*dp[i-1]-dp[i-4]
        if(n==1) return 3;
        if(n==2) return 8;
        long long mod=pow(10,9)+7;
        vector<long long> dp(n+1,0);
        dp[0]=1;
        dp[1]=2;
        dp[2]=4;
        dp[3]=7;
        for(int i=4;i<=n;i++) 
        {   // 因为dp中所有元素都已经取模,可能存在2*dp[i-1]<dp[i-4]
            dp[i]=(2*dp[i-1]-dp[i-4]+mod)%mod;
        }
        // 现在考虑加上A,可以分为加上一个A或者不加A
        long long result=0;
        result+=dp[n];
        for(int i=0;i<n;i++) // A左边有i个字符,右边有n-1-i个字符
        {
            result+=(dp[i]*dp[n-1-i])%mod;
            result%=mod;
        }
        return result;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值