-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclimbing-stairs.js
More file actions
35 lines (29 loc) · 811 Bytes
/
climbing-stairs.js
File metadata and controls
35 lines (29 loc) · 811 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// https://leetcode.com/problems/climbing-stairs/
// Related Topics: Dynamic Programming
// Difficulty: Easy
/*
Initial thoughts:
Considering the fact that the ways we can reach step i equals
the ways we can reach step i-1 + the ways we can reach step i-2
we approach the problem like calculating the Fibonacci number
by calculating every next step based on the last two, starting from
our two base cases where for n === 1 there is one way and for n === 2
there are two ways to reach step n.
Time complexity: O(n)
Space complexity: O(1)
*/
/**
* @param {number} n
* @return {number}
*/
const climbStairs = n => {
if (n === 1) return 1;
let first = 1,
second = 2;
for (let i = 3; i <= n; i++) {
const third = first + second;
first = second;
second = third;
}
return second;
};