- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/12900
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/2xn 타일링
풀이 시간 : 12분
class Solution {
public int solution(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = (dp[i-1] + dp[i-2]) % 1000000007;
}
return dp[n];
}
}
class Solution {
private static final int MOD = 1000000007;
public int solution(int n) {
// 기저 사례
if (n == 1) return 1;
if (n == 2) return 2;
// 행렬 거듭제곱: [[1,1],[1,0]]^n
long[][] result = matrixPower(new long[][]{{1, 1}, {1, 0}}, n);
// T(n) = F(n+1) = result[0][0]
return (int)(result[0][0] % MOD);
}
private long[][] matrixPower(long[][] matrix, int power) {
if (power == 1) {
return copyMatrix(matrix);
}
if (power % 2 == 0) {
long[][] half = matrixPower(matrix, power / 2);
return multiplyMatrix(half, half);
} else {
return multiplyMatrix(matrix, matrixPower(matrix, power - 1));
}
}
private long[][] multiplyMatrix(long[][] a, long[][] b) {
long[][] result = new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
result[i][j] = (result[i][j] + a[i][k] * b[k][j]) % MOD;
}
}
}
return result;
}
private long[][] copyMatrix(long[][] matrix) {
long[][] copy = new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
copy[i][j] = matrix[i][j];
}
}
return copy;
}
}