算法作业_20(2017.5.4第十一周)
来源:互联网 发布:大数据建模 编辑:程序博客网 时间:2024/06/05 00:22
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:
- '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).
还是前一个问题,感觉前面用三维数据比较复杂,所以换一种比较简单的做法,用一维数组来解答,分别定义六个数组: long []a0 = new long[n]; //a0表示以A为结尾,含有0个A的字符串
long []a1 = new long[n]; //a1表示以以A为结尾,含有1个A的字符串
long []l0 = new long[n]; //l0表示以L为结尾,含有0个A的字符串
long []l1 = new long[n]; //l1表示以L为结尾,含有1个A的字符串
long []p0 = new long[n]; //p0表示以P为结尾,含有0个A的字符串
long []p1 = new long[n]; //p1表示以P为结尾,含有1个A的字符串
当n=1和n=2时,容易求出:
a0a1l0l1p0p1n=1011010n=2022121
所以可以得出递推公式:
a1[i] = (a0[i-1]+l0[i-1]+p0[i-1])
l0[i] = (a0[i-2]+p0[i-2]+a0[i-1]+p0[i-1])
l1[i] = (a1[i-2]+p1[i-2]+a1[i-1]+p1[i-1])
p0[i] = (a0[i-1]+l0[i-1]+p0[i-1])
p1[i] = (a1[i-1]+l1[i-1]+p1[i-1])
以a 和p 结尾的只需要考虑前面一项,以l 结尾的要考虑前面一项。代码如下:
public class Solution { public int checkRecord(int n) { if(n==1) return 3; if(n==2) return 8; int mod = (int)(Math.pow(10,9)+7); long []a0 = new long[n]; long []a1 = new long[n]; long []l0 = new long[n]; long []l1 = new long[n]; long []p0 = new long[n]; long []p1 = new long[n]; a0[0]=0;a1[0]=1;l0[0]=1;l1[0]=0;p0[0]=1;p1[0]=0; a0[1]=0;a1[1]=2;l0[1]=2;l1[1]=1;p0[1]=2;p1[1]=1; for(int i = 2;i<n;i++){ a1[i] = (a0[i-1]+l0[i-1]+p0[i-1])%mod; l0[i] = (a0[i-2]+p0[i-2]+a0[i-1]+p0[i-1])%mod; l1[i] = (a1[i-2]+p1[i-2]+a1[i-1]+p1[i-1])%mod; p0[i] = (a0[i-1]+l0[i-1]+p0[i-1])%mod; p1[i] = (a1[i-1]+l1[i-1]+p1[i-1])%mod; } long res = a0[n-1]+a1[n-1]+l0[n-1]+l1[n-1]+p0[n-1]+p1[n-1]; return (int)(res%mod); }}
- 算法作业_20(2017.5.4第十一周)
- 算法作业_19(2017.5.3第十一周)
- 算法第十一周作业01
- 作业4_20
- 第十一周作业 1
- 第十一周作业 2
- 第十一周作业 3.0
- 第十一周作业
- 第十一周作业2
- 第十一周作业
- 第十一周作业2
- 第十一周作业 1
- 第十一周java作业
- 第十一周作业
- 第十一周java作业
- 算法结构与设计基础作业第十一周
- 算法课第十一周作业 | Longest Consecutive Sequence
- 第十一周作业(1)
- 编写stream minidriver
- DDMS不显示文件树
- svn 上传ios @2x图片时出错
- 推荐系统架构
- IoT (Internet of Things)资源汇总
- 算法作业_20(2017.5.4第十一周)
- 禅道-从windows7迁移至ubuntu14.04之一
- 解决windows下 cd 无法切换盘符目录
- Java学习之路一
- TotoiseSVN-小乌龟的使用方法
- AVStream介绍
- MAC下解决sudo: /etc/sudoers is owned by uid 501, should be 0的问题
- App 为什么收不到推送?
- android apk的大小优化