I am working on the project euler lattice path problem in Javascript. I used the recursive method and solved it in project euler. Below is my function,
const latticePathsRecursive = (m, n = m) => {
if (m < 0 || n < 0) return 0;
if (m === 0 && n === 0) return 1;
return (latticePathsRecursive(m - 1, n) + latticePathsRecursive(m, n - 1));
}
I tried the same in Hackerrank(test cases have both square & rectangular grid) but all the hidden test cases timed out
and failed.
So I tried using Combinatorial Solution and except for the sample test case and one hidden test case all the other test cases failed - wrong answer
.
I can't figure out where it went wrong. But why 3 test cases pass and the rest throws wrong answer
? Am I missing something while using the formula here?
const latticePathsCombinatorial = (a, b) => {
const factorial = (number) => {
if (number === 1 || number === 0) {
return 1;
} else {
return number * factorial(number - 1);
}
}
let n = a + b,
k = a;
// 'n choose k' = n! / (k! * (n - k)!)
return factorial(n) / (factorial(k) * factorial(n - k));
}
Thanks in advance.