zoukankan      html  css  js  c++  java
  • 【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).

    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.

    解题思路:根据题目要求,A最多可以出现1次,同时L不能连续出现三个及以上。显然,所有符合条件的出席记录 = 不包含A的出席记录数 + 包含A的出席记录数。首先来看不包含A的出席记录数怎么求,假设dp[i][0]和dp[i][1]分别表示第i个元素为L和为P时候可以构成的符合条件的出席记录数,那么有dp[i][1] = dp[i-1][0] + dp[i-1][1],因为如果第i位是P,那么i-1是L或者是P都是允许的;同时有 dp[i][0] = dp[i-2][0]  + dp[i-2][1]*2,这是因为如果第i位是L,如果i-2位也是L的话,则第i-1位就只能是P,而i-2是P的话,第i-2位是L或者是P都是允许的。接下来看包含A的情况,假设A放在出席记录的第i位的位置,出席记录就会被分割成[0:i-1]和[i+1:n]两段,这两段也只能包含L和P,所以正好又可以转化为第一种情况中已经计算出来的dp[i-1]和dp[n-i]两种,A在第i位符合条件的出席记录数就是dp[i-1]*dp[n-i],依次累计A在第0位~第N-1位的出席记录数总和,再加上第一种情况的个数,即为最后的结果。

    代码如下:

    class Solution(object):
        def checkRecord(self, n):
            """
            :type n: int
            :rtype: int
            """
            MOD = pow(10,9) + 7
            if n <= 1:
                return  [0,3][n]
            dp = []
            for i in range(n): #0:L,1:P
                dp.append([0]*2)
            dp[0][0] = dp[0][1] = 1
            dp[1][0] = dp[1][1] = 2
            for i in range(2,n):
                dp[i][0] = (dp[i-2][0] % MOD + (dp[i-2][1]*2) % MOD) % MOD
                dp[i][1] = (dp[i-1][0] % MOD + dp[i-1][1] % MOD) % MOD
            res = 0
            for i in range(n):
                if i == 0 or i == n - 1:
                    res += (dp[n-2][0] + dp[n-2][1])
                else:
                    res += (dp[i-1][0] + dp[i-1][1]) * (dp[n-i-2][0] + dp[n-i-2][1])
            return (res + dp[-1][0] + dp[-1][1]) % (pow(10, 9) + 7)
  • 相关阅读:
    JS中的prototype
    mustache.js渲染带事件的模板
    PHP的UTF-8中文转拼音处理类(性能已优化至极致)
    js
    git的作用和原理(待续)
    linux简单配置
    sql查询字段值长度判断是否18位
    sql查询重复值
    java获取某一字段日期并增加7天存入另一字段
    数据库20190206////2019-02-06 00:00:00.000日期格式页面转换
  • 原文地址:https://www.cnblogs.com/seyjs/p/10420247.html
Copyright © 2011-2022 走看看