元宝 LeetCode 552. Student Attendance Record II Java Implement

发布时间:2026/10/16 8:53:45
元宝    LeetCode 552. Student Attendance Record II Java Implement Encode both rules into one state machine: how many A’s used (0/1) × trailing consecutive L’s (0/1/2) → 6 states.Solution 1: DP — O(n) time, O(1) space (recommended)class Solution {private static final long MOD 1_000_000_007L;public int checkRecord(int n) { long[][] dp new long[2][3]; dp[0][0] 1; // empty prefix for (int i 0; i n; i) { long[][] next new long[2][3]; for (int a 0; a 2; a) { for (int l 0; l 3; l) { long v dp[a][l]; if (v 0) continue; next[a][0] (next[a][0] v) % MOD; // append P if (a 0) next[1][0] (next[1][0] v) % MOD; // append A if (l 2) next[a][l 1] (next[a][l 1] v) % MOD; // append L } } dp next; } long ans 0; for (int a 0; a 2; a) for (int l 0; l 3; l) ans (ans dp[a][l]) % MOD; return (int) ans; }}Solution 2: Matrix exponentiation — O(log n)Flatten the states with“idx a * 3 l”, fill a 6×6 matrix using the same three transitions, binary-exponentiate it, then sum column 0 (the initial vector is“e[(0,0)]”). Full code is in the file.Common pitfallsUse“long” for intermediates —“int” overflows on the product of two ~1e9 values.“No“LLL”” means trailing L’s may reach at most 2; prune the transition that would make it 3.“n 0” returns 1 (the empty record counts).Both versions were cross-checked against brute-force enumeration for n 0…8, and they agree at“n 10101” →“183236316”.

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询