Skip to content

Commit dbf62d7

Browse files
committed
Add climbing-stairs solution
1 parent ed8b53f commit dbf62d7

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

climbing-stairs/Jeehay28.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
6+
// Time Complexity: O(n^2)
7+
// First O(n): From the loop that runs up to n times.
8+
// Second O(n): From the factorial calculations in each iteration.
9+
// overall time complexity is O(n^2).
10+
11+
// Space Complexity: O(n)
12+
// the factorial function's recursion has a space complexity of O(n)
13+
// O(1) means constant space complexity. It implies that the amount of memory used does not grow with the size of the input.
14+
// The other variables in the function only use a constant amount of space, resulting in an O(1) space usage.
15+
16+
var climbStairs = function (n) {
17+
let ways = 0;
18+
19+
let maxStepTwo = Math.floor(n / 2);
20+
21+
const factorial = (num) => {
22+
if (num === 0 || num === 1) {
23+
return 1;
24+
}
25+
26+
for (let i = 2; i <= num; i++) {
27+
return num * factorial(num - 1);
28+
}
29+
};
30+
31+
for (let i = 0; i <= maxStepTwo; i++) {
32+
const stepTwo = i;
33+
const stepOne = n - 2 * i;
34+
const steps = stepTwo + stepOne;
35+
36+
ways += factorial(steps) / (factorial(stepTwo) * factorial(stepOne));
37+
}
38+
39+
return ways;
40+
};

0 commit comments

Comments
 (0)