|
| 1 | +class Solution { |
| 2 | + // Helper function to recursively count valid attendance records |
| 3 | + int solve(int index, int n, int absCount, int lateCount, vector<vector<vector<int>>>& dp) { |
| 4 | + const int MOD = 1e9 + 7; // Define the modulo constant |
| 5 | + |
| 6 | + // Base case: If we've reached the end of the attendance record, return 1 |
| 7 | + if (index >= n) { |
| 8 | + return 1; |
| 9 | + } |
| 10 | + |
| 11 | + // If the result is already computed, return the cached value |
| 12 | + if (dp[index][absCount][lateCount] != -1) { |
| 13 | + return dp[index][absCount][lateCount]; |
| 14 | + } |
| 15 | + |
| 16 | + int ans = 0; // Initialize the answer for this state |
| 17 | + |
| 18 | + // Absent module: If absences are less than 1, we can add an 'A' |
| 19 | + if (absCount < 1) { |
| 20 | + ans = ((ans % MOD) + solve(index + 1, n, absCount + 1, 0, dp) % MOD) % MOD; |
| 21 | + } |
| 22 | + |
| 23 | + // Late module: If consecutive lates are less than 2, we can add an 'L' |
| 24 | + if (lateCount < 2) { |
| 25 | + ans = ((ans % MOD) + solve(index + 1, n, absCount, lateCount + 1, dp) % MOD) % MOD; |
| 26 | + } |
| 27 | + |
| 28 | + // Present module: We can always add a 'P' |
| 29 | + ans = ((ans % MOD) + solve(index + 1, n, absCount, 0, dp) % MOD) % MOD; |
| 30 | + |
| 31 | + // Store the result in the dp array and return it |
| 32 | + return dp[index][absCount][lateCount] = ans; |
| 33 | + } |
| 34 | +public: |
| 35 | + int checkRecord(int n) { |
| 36 | + int absCount=0; |
| 37 | + int lateCount=0; |
| 38 | + int index=0; |
| 39 | + // Initialize a 3D dp array with dimensions [n][2][3] and all values set to -1 |
| 40 | + vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(3, -1))); |
| 41 | + |
| 42 | + // Call the solve function starting from index 0 with 0 absences and 0 lates |
| 43 | + return solve(index,n,absCount,lateCount,dp); |
| 44 | + |
| 45 | + } |
| 46 | +}; |
0 commit comments