Student Attendance Record II

本文深入探讨了一种算法,用于计算长度为n的所有可能考勤记录数量,这些记录被视为奖励性的,即最多只包含一个缺席(A)或连续两个迟到(L)。文章通过分情况讨论,介绍了如何使用动态规划解决此问题,包括不含缺席记录和含一次缺席记录的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 

思路:这个题看到了九章的答案精妙之处,良心网站。我搜了好多讲解都看不是特别懂,只有九章,一目了然。真心赞一个!

分情况讨论:因为A只出现一次,那么我们

without A的情况

dp[i] 表示,不包含A的长度为i的valid number. 由于尾巴只能是有P, L组合而成,那么尾巴valid的是: P, PL, PLL

dp[i] = dp[i-1] + dp[i-2] + dp[i - 3]

With A, 循环i,sum all of  [0....i - 1] A [i + 1.....n] => dp[i-1] * dp[n - (i+ 1) + 1] => dp[i-1] * dp[n - i];

注意初始值init: dp[0] = 1

dp[1] = 2, P, L

dp[2] = 4, PL, LP, LL, PP

class Solution {
    private static int MOD = 1000000007;
    public int checkRecord(int n) {
        if(n <= 0) {
            return 0;
        }
        long[] dp = new long[n + 1];
        // without A;
        // end with P, PL, PLL.
        // dp[i] 代表长度为i,不包含A的valid String 数目;
        // dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
        dp[0] = 1;
        if(n >= 1) {
            dp[1] = 2;
        }
        
        if(n >= 2) {
            dp[2] = 4;
        }
        
        for(int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
            dp[i] = dp[i] % MOD;
        }
        
        // with A;
        // [0 ... i -1] A [i + 1... n];
        long res = 0;
        for(int i = 1; i <= n; i++) {
            res += dp[i-1] * dp[n - i];
            res = res % MOD;
        }
        return (int) (dp[n] + res) % MOD;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值