-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclimbing_stairs.rs
44 lines (42 loc) · 947 Bytes
/
climbing_stairs.rs
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
36
37
38
39
40
41
42
43
44
///
/// Problem: Climbing Stairs
///
/// You are climbing a staircase. It takes `n` steps to reach the top.
/// Each time you can either **climb 1 step or 2 steps**.
///
/// Return **the number of distinct ways** you can climb to the top.
///
/// **Example 1:**
/// ```plaintext
/// Input: n = 2
/// Output: 2
/// Explanation: (1 step + 1 step) OR (2 steps at once)
/// ```
///
/// **Example 2:**
/// ```plaintext
/// Input: n = 3
/// Output: 3
/// Explanation: (1+1+1), (1+2), (2+1)
/// ```
///
/// **Constraints:**
/// - `1 <= n <= 45`
///
/// # Solution:
/// - **Time Complexity:** `O(n)`
/// - **Space Complexity:** `O(1)`
impl Solution {
pub fn climb_stairs(n: i32) -> i32 {
if n == 1 {
return 1;
}
let (mut prev2, mut prev1) = (1, 2);
for _ in 3..=n {
let current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
prev1
}
}