File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments