为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode552. 学生出勤记录 II | Student Attendance Record II

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10414568.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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.  

Note: The value of n won't exceed 100,000.


给定一个正整数 n,返回长度为 n 的所有可被视为可奖励的出勤记录的数量。 答案可能非常大,你只需返回结果mod 109 + 7的值。

学生出勤记录是只包含以下三个字符的字符串:

  1. 'A' : Absent,缺勤
  2. 'L' : Late,迟到
  3. 'P' : Present,到场

如果记录不包含多于一个'A'(缺勤)或超过两个连续的'L'(迟到),则该记录被视为可奖励的。

示例 1:

输入: n = 2
输出: 8 
解释:
有8个长度为2的记录将被视为可奖励:
"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
只有"AA"不会被视为可奖励,因为缺勤次数超过一次。

注意:n 的值不会超过100000。


Runtime: 276 ms
Memory Usage: 19.7 MB
 1 class Solution {
 2     func checkRecord(_ n: Int) -> Int {
 3         var M:Int = 1000000007;
 4         var P:[Int] = [Int](repeating:0,count:n + 1)
 5         var PorL:[Int] = [Int](repeating:0,count:n + 1)
 6         P[0] = 1
 7         PorL[0] = 1
 8         PorL[1] = 2
 9         for i in 1...n
10         {
11             P[i] = PorL[i - 1]
12             if i > 1
13             {
14                 PorL[i] = (P[i] + P[i - 1] + P[i - 2]) % M
15             }
16         }
17         var res:Int = PorL[n];
18         for i in 0..<n
19         {
20             var t:Int = (PorL[i] * PorL[n - 1 - i]) % M
21             res = (res + t) % M
22         }
23         return res
24     }
25 }

 

posted @ 2019-02-21 18:48  为敢技术  阅读(360)  评论(0编辑  收藏  举报