public int numTilings(int N) { // dp转移方程: dp(n) = 2 * dp(n-1) + dp(n-3), 时间复杂度O(N), 空间复杂度O(1)
if (N == 0) {
return 0;
}
if (N == 1) {
return 1;
}
if (N == 2) {
return 2;
}
int mod = (int)(Math.pow(10, 9) + 7);
int n1 = 1, n2 = 2, n3 = 5;
for (int i = 4; i <= N; i++) {
int temp = (2 * n3 % mod + n1) % mod; // 2*n3+n1 会超过int的最大值(2147483647, 2开头10位数), 所以要对 2*n3 进行mod(1000000007, 1开头10位数)
n1 = n2;
n2 = n3;
n3 = temp;
}
return n3;
}
原文地址:https://www.cnblogs.com/lasclocker/p/11405819.html
时间: 2024-10-02 16:45:41