728x90
tiling
문제
세로 길이 2, 가로 길이 n인 2 x n 보드가 있습니다. 2 x 1 크기의 타일을 가지고 이 보드를 채우는 모든 경우의 수를 리턴해야 합니다.
입력
let output = tiling(2);
console.log(output); // --> 2
output = tiling(4);
console.log(output); // --> 5
/*
2 x 4 보드에 타일을 놓는 방법은 5가지
각 타일을 a, b, c, d로 구분
2 | a b c d
1 | a b c d
let tiling = function (n) {
// 인덱스를 직관적으로 관리하기 위해
// 앞 부분을 의미없는 데이터(dummy)로 채운다.
const memo = [0, 1, 2];
// 재귀를 위한 보조 함수(auxiliary function)을 선언)
const aux = (size) => {
// size = 5
// 이미 해결한 문제는 풀지 않는다.
if (memo[size] !== undefined) return memo[size];
if (size <= 2) return memo[n];
memo[size] = aux(size - 1) + aux(size - 2);
// memo[5] = aux(4) + aux(3) = 2 * aux(3) + aux(2) = 2{aux(2) + aux(1)} + aux(2) = 8
// aux(4) = aux(3) + aux(2)
// aux(3) = aux(2) + aux(1)
return memo[size];
};
return aux(n);
};
728x90
'코플릿 > toyproblem' 카테고리의 다른 글
toy problem 07 (0) | 2021.10.28 |
---|---|
toy problem 06 (0) | 2021.10.28 |
toy problem 14 (0) | 2021.10.26 |
toy problem 04 (0) | 2021.10.21 |
toy problem 03 (0) | 2021.10.20 |