70. Climbing Stairs Easy

@problem@discussion
#Math#Dynamic Programming#Memoization



1/**
2 * [70] Climbing Stairs
3 *
4 * You are climbing a staircase. It takes n steps to reach the top.
5 * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
6 *  
7 * Example 1:
8 * 
9 * Input: n = 2
10 * Output: 2
11 * Explanation: There are two ways to climb to the top.
12 * 1. 1 step + 1 step
13 * 2. 2 steps
14 * 
15 * Example 2:
16 * 
17 * Input: n = 3
18 * Output: 3
19 * Explanation: There are three ways to climb to the top.
20 * 1. 1 step + 1 step + 1 step
21 * 2. 1 step + 2 steps
22 * 3. 2 steps + 1 step
23 * 
24 *  
25 * Constraints:
26 * 
27 * 1 <= n <= 45
28 * 
29 */
30pub struct Solution {}
31
32// problem: https://leetcode.com/problems/climbing-stairs/
33// discuss: https://leetcode.com/problems/climbing-stairs/discuss/?currentPage=1&orderBy=most_votes&query=
34
35// submission codes start here
36
37impl Solution {
38    pub fn climb_stairs(n: i32) -> i32 {
39        if n < 2 {
40            return 1;
41        } else if n == 2 {
42            return 2;
43        }
44
45        let mut one = 2;
46        let mut two = 1;
47        for _ in 3..n + 1 {
48            let tmp = one + two;
49            two = one;
50            one = tmp;
51        }
52        one        
53    }
54}
55
56// submission codes end
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_70() {
64        assert_eq!(Solution::climb_stairs(3), 3);
65        assert_eq!(Solution::climb_stairs(1), 1);
66        assert_eq!(Solution::climb_stairs(2), 2);
67        assert_eq!(Solution::climb_stairs(4), 5);
68    }
69}
70


Back
© 2025 bowen.ge All Rights Reserved.