알고리즘
프로그래머스 2 x n 타일링 (JAVA)
박카스마시며코딩
2022. 6. 13. 22:43
https://programmers.co.kr/learn/courses/30/lessons/12900
코딩테스트 연습 - 2 x n 타일링
가로 길이가 2이고 세로의 길이가 1인 직사각형모양의 타일이 있습니다. 이 직사각형 타일을 이용하여 세로의 길이가 2이고 가로의 길이가 n인 바닥을 가득 채우려고 합니다. 타일을 채울 때는
programmers.co.kr
저는 dp를 이용해 문제를 해결하였습니다.
dp[depth] = dp[depth -1] + dp[depth -2] 공식을 세워 dp를 풀었습니다.
class Solution {
private static final int LIMIT = 1_000_000_007;
private static final int NOT_VALID = 0;
public int solution(int n) {
int answer = 0;
int[] dp = new int[n +1];
answer = dfs(n,dp);
return answer;
}
private int dfs(int depth, int[] dp){
if(dp[depth] != NOT_VALID){
return dp[depth];
}
if(depth == 1){
return 1;
}
if(depth == 2){
return 2;
}
return dp[depth] = (dfs(depth-1,dp) + dfs(depth-2,dp)) % LIMIT;
}
}