题目描述:
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:
- '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).
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', 'L', 'P'三种字符构成,若其中包含的'A'不超过1个,并且不包含连续的3个或3个以上'L',则称该字符串有效。
给定正整数n,返回长度为n的“有效字符串”的个数。
由于结果可能会很大,对1e9 + 7取模。
注意:n的值不超过100,000
解题思路:
动态规划(Dynamic Programming)
利用dp[n][A][L]表示长度为n,包含A个字符'A',以L个连续的'L'结尾的字符串的个数。
状态转移方程:
dp[n][0][0] = sum(dp[n - 1][0]) dp[n][0][1] = dp[n - 1][0][0] dp[n][0][2] = dp[n - 1][0][1] dp[n][1][0] = sum(dp[n - 1][0]) + sum(dp[n - 1][1]) dp[n][1][1] = dp[n - 1][1][0] dp[n][1][2] = dp[n - 1][1][1] 初始令dp[1] = [[1, 1, 0], [1, 0, 0]]
由于dp[n]只和dp[n - 1]有关,因此上述转移方程可以使用滚动数组,将空间复杂度降低一维。
Java代码:
public class Solution {
private final int MOD = 1000000007;
public long sum(int[] nums) {
long ans = 0;
for (int n : nums) ans += n;
return ans % MOD;
}
public int checkRecord(int n) {
int dp[][] = {{1, 1, 0}, {1, 0, 0}};
for (int i = 2; i <= n; i++) {
int ndp[][] = {{0, 0, 0}, {0, 0, 0}};
ndp[0][0] = (int)sum(dp[0]);
ndp[0][1] = dp[0][0];
ndp[0][2] = dp[0][1];
ndp[1][0] = (int)((sum(dp[0]) + sum(dp[1])) % MOD);
ndp[1][1] = dp[1][0];
ndp[1][2] = dp[1][1];
dp = ndp;
}
return (int)((sum(dp[0]) + sum(dp[1])) % MOD);
}
}
本文链接:http://bookshadow.com/weblog/2017/04/16/leetcode-student-attendance-record-ii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。