【LeetCode】552. Student Attendance Record II

来源:互联网 发布:能看回放的网络电视 编辑:程序博客网 时间:2024/06/06 05:24

【LeetCode】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:

  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)

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

【输入输出】

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. 


【解题思路】

动态规划(DP):1. ans[n][a][l]表示总共n个字符,其中A字符最多有a个,结尾处最多有l个L字符2. 操作1:在结尾加P字符,ans[n][a][l] += ans[n-1][a][2] (如PLL结尾加P得到PLLP应该算入ans[4][0][0])3. 操作2:在结尾加A字符,ans[n][a][l] += ans[n-1][a-1][2]4. 操作3:在结尾加L字符,ans[n][a][l] += ans[n-1][a][l-1] (如PLL结尾不能加L)5. 返回ans[n][1][2]6. 由于n可取100,000,保存全部结果可能MLE,故加入flag参量,只保存n和n-1的结果。


【代码】

class Solution {public:int checkRecord(int n) {const int con = (int)(1e9 + 7);int ans[2][2][3] = { { { 1, 1, 1 }, { 1, 1, 1 } } }, flag = 0;for (int i = 1; i <= n; i++) {flag = 1 - flag;for (int a = 0; a < 2; a++) {for (int l = 0; l < 3; l++) {ans[flag][a][l] = ans[1 - flag][a][2];if (a > 0) ans[flag][a][l] = (ans[flag][a][l] + ans[1 - flag][a - 1][2]) % con;if (l > 0) ans[flag][a][l] = (ans[flag][a][l] + ans[1 - flag][a][l - 1]) % con;}}}return ans[flag][1][2];}};
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 购买方发票丢了怎么办 普票发票联丢失怎么办 唯品金融没还款怎么办 金点原子锁打不开了怎么办 87彩店注册不了怎么办 微店如果不退款怎么办 微信上微商被骗怎么办 微商代理不做了怎么办 微店拒收不退款怎么办 在微商买东西被骗怎么办 云集买家买东西不退款怎么办 微信红包密码忘记了怎么办 微信购物不退货怎么办 微信隐私设置无法添加怎么办 微信支付被限额怎么办 微信发现没有购物怎么办 微信转账钱被骗怎么办 玩连环夺宝输了好多钱怎么办 厘米秀换不了装怎么办 社保只缴纳两年怎么办 502盖子粘到手上怎么办 口红粘在盖子上怎么办 玫瑰手杖永久错过了怎么办 手指沾到502胶水怎么办 我退款了货到了怎么办 世纪天成账号被盗什么也没绑怎么办 韩国电话卡不想用怎么办2018 汽车没有年检交警抓到怎么办 ios软件未受信任怎么办 淘宝开店被管理了怎么办 微店网络异常025怎么办 商家给买家返款转错了怎么办 淘宝号限制下单怎么办 淘宝退货单号填错了怎么办 淘宝买家申请退款不退货怎么办 不支持7天无理由怎么办 淘宝上不给退货怎么办 网购衣服买小了怎么办 淘宝上全球购买到假货怎么办 京东全球购税费怎么办 代购被海关税了怎么办