算法作业_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:

  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).

还是前一个问题,感觉前面用三维数据比较复杂,所以换一种比较简单的做法,用一维数组来解答,分别定义六个数组:

             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);    }}



0 0