Created
March 17, 2017 04:51
-
-
Save vitkarpov/e295c8e2a662dafdf36526229b392004 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", 8.1.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Находит количество всех возможных вариантов | |
* как можно добраться до n-й ступени по лестнице, | |
* если можно пройти 1, 2 или 3 ступени за один шаг. | |
* | |
* Используется кеш, ссылка на который передается вторым аргументом | |
* через все рекурсивные вызовы функции. | |
* | |
* @param {number} n | |
* @param {array<number>} cache | |
* @returns {number} | |
*/ | |
function countWays(n, cache = []) { | |
if (n < 0) { | |
return 0; | |
} | |
if (n === 0) { | |
return 1; | |
} | |
if (cache[n]) { | |
return cache[n]; | |
} | |
cache[n] = countWays(n - 1, cache) + countWays(n - 2, cache) + countWays(n - 3, cache); | |
return cache[n]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment