552. Student Attendance Record II

本文提供了一种解决LeetCode上学生考勤记录II问题的有效方法,通过数学推导的方式,采用O(N)复杂度的动态规划算法来求解连续考勤记录的所有可能性。文中详细解释了如何理解题目中“超过两个连续迟到”的含义,并给出了具体的代码实现。

Problem refer: https://leetcode.com/problems/student-attendance-record-ii/description

// My solution:
// A good mathmatical derivation problem.
// But it makes me confused with the word: "more than two continuous 'L' (late)".
// And finally find it actually represents "LLL".
// The last solution refers to the discuss: 
// https://discuss.leetcode.com/topic/86696/share-my-o-n-c-dp-solution-with-thinking-process-and-explanation

class Solution {
public:
    static const int N = 100000 + 1;
    static const int MOD = 1000000000 + 7;
    int P[N],L[N],A[N];
    int ans[N];
    
    int calc(int n) {
        if (ans[n]) return ans[n];
        calc(n-1);
        
        P[n] = (P[n-1] + A[n-1])%MOD + L[n-1];
        P[n] %= MOD;
        
        L[n] = ((P[n-1] + A[n-1])%MOD + A[n-2])%MOD + P[n-2];
        L[n] %= MOD;
        A[n] = (A[n-1] + A[n-2])%MOD + A[n-3];
        A[n] %= MOD;
        ans[n] = (P[n] + L[n])%MOD + A[n];
        ans[n]%=MOD;
        return ans[n];
    }
    int checkRecord(int n) {
        memset(ans, 0, sizeof ans);
        P[1]=L[1]=A[1]=1;
        ans[1] = 3;
    
        P[2] = L[2] = 3;
        A[2] = 2;
        ans[2] = 8;
    
        P[3] = 8;
        L[3] = 7;
        A[3] = 4;
        ans[3] = 19;
        return calc(n);
    }
};

 

转载于:https://www.cnblogs.com/kkrisen/p/7897923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值