552. Student Attendance Record II
来源:互联网 发布:开发者 读书app 知乎 编辑:程序博客网 时间:2024/06/06 08:34
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:
- 'A' : Absent.
- 'L' : Late.
- '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 = 2Output: 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.
利用动态规划解题。初始化数组P,L,A,PLP,PLL来存储之前的状态,动态规划的原则如下:PLP[i] = PLL[i - 1] + PLP[i - 1];PLL[i] = PLP[i - 2] + PLP[i - 1];P[i] = P[i - 1] + L[i - 1] + A[i - 1];A[i] = PLP[i - 1] + PLL[i - 1];L[i] = P[i - 1] + P[i - 2] + A[i - 1] + A[i - 2];根据以上规则写代码,代码如下:
public class Solution { public int checkRecord(int n) { if (n == 1) { return 3; } if (n == 2) { return 8; } long[] PLP = new long[n + 1]; long[] PLL = new long[n + 1]; long[] P = new long[n + 1]; long[] L = new long[n + 1]; long[] A = new long[n + 1]; PLP[0] = 0; PLP[1] = 1; PLP[2] = 2; PLL[0] = 0; PLL[1] = 1; PLL[2] = 2; P[0] = 0; P[1] = 1; P[2] = 3; L[0] = 0; L[1] = 1; L[2] = 3; A[0] = 0; A[1] = 1; A[2] = 2; long sumA = 2; for (int i = 3; i <= n; i ++) { PLP[i] = PLL[i - 1] + PLP[i - 1]; PLL[i] = PLP[i - 2] + PLP[i - 1]; P[i] = P[i - 1] + L[i - 1] + A[i - 1]; A[i] = PLP[i - 1] + PLL[i - 1]; L[i] = P[i - 1] + P[i - 2] + A[i - 1] + A[i - 2]; PLP[i] %= 1000000007; PLL[i] %= 1000000007; P[i] %= 1000000007; A[i] %= 1000000007; L[i] %= 1000000007; } return (int)((P[n] + L[n] + A[n]) % 1000000007); }}
0 0
- 552. Student Attendance Record II
- 552. Student Attendance Record II
- 552. Student Attendance Record II
- 552. Student Attendance Record II
- 552. Student Attendance Record II
- 552. Student Attendance Record II
- 【LeetCode】552. Student Attendance Record II
- [LeetCode]552. Student Attendance Record II
- LeetCode 552. Student Attendance Record II
- leetcode 552. Student Attendance Record II
- leetcode#552. Student Attendance Record II
- [leetcode]552. Student Attendance Record II
- leetcode552. Student Attendance Record II
- [Leetcode] 552. Student Attendance Record II 解题报告
- leetcode_552.Student Attendance Record II ? 待解决
- [LeetCode] DP之 Student Attendance Record II
- Student Attendance Record I
- Student Attendance Record I
- My97DatePicker 默认当前时间 Java
- Sql Server服务远程过程调用失败
- Linux下NFS设定方法
- 顺序栈
- [数据结构] 栈与队列
- 552. Student Attendance Record II
- 二进制方式安装docker
- 最基础的启动脚本编写
- java中sleep()的用法
- poj 1191 把一个矩形分成n块,求其均方差最小 dp
- MySQL日记——使用脚本批量插入数据
- Adding DNS addresses into /etc/resolv.conf
- 抽象类与接口学习笔记
- Python语言中的类型之字符串型--Python(11)