Problem
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.
Solution
C++
DFS w/ memorization (stack overflow)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Solution { public: int checkRecord(int n) { m_ = vector<vector<int>>(n + 1, vector<int>(6, 0)); if (n >= 100000) return 0; return dfs(n, 1, 2); } private: vector<vector<int>> m_; // number of solutions of using at most A As and L Ls long dfs(int n, int A, int L) { if (n == 0) return 1; int key = A * 3 + L; if (m_[n][key]) return m_[n][key]; long ans = 0; ans += dfs(n - 1, A, 2); // 'P', reset number of Ls if (A > 0) ans += dfs(n - 1, A - 1, 2); // 'A', reset number of Ls if (L > 0) ans += dfs(n - 1, A, L - 1); // 'L' return m_[n][key] = (ans % 1000000007); } }; |
DP
Time complexity: O(n)
Space complexity: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua // Running time: 129 ms class Solution { public: int checkRecord(int n) { constexpr int kMod = 1000000007; vector<long> dp(6, 1); for (int i = 1; i <= n; ++i) { vector<long> tmp(6); for (int A = 0; A <= 1; ++A) for (int L = 0; L <= 2; ++L) { const int key = getKey(A, L); tmp[key] += dp[getKey(A, 2)]; if (A > 0) tmp[key] += dp[getKey(A - 1, 2)]; if (L > 0) tmp[key] += dp[getKey(A, L - 1)]; tmp[key] %= kMod; } dp.swap(tmp); } return dp[5]; } private: inline int getKey(int A, int L) { return A * 3 + L; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment