70. Climbing Stairs
Question:
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Source code
Version 1
Idea:
We must find the reqular pattern. As example mentioned, n = 2 -> output: 2, n = 3 -> output: 3.
You can derive n = 4, n = 5, ...ect. My answer is as below and you can get the reqular result:
n = 4 -> Output: 5 // 2 + 3
n = 5 -> Output: 8 // 3 + 5
n = 6 -> Output: 13 // 5 + 8
n = 7 -> Output: 21 // 8 + 13
(Results: 1 2 3 5 8 13 21 ...)
Isn't it like classical problem of Fibonacci Sequence? So, I directly think recursion can solve it. The approach is as below, but the recursion can't pass the submission, because it will show Time Limit Exceeded when n = 44.
1 | class Solution { |
Version 2
Idea:
The strategy of second approach is an iterator. We can use for loop instead of recursion. Very simple coding as below and it can pass the submission.
1 | class Solution { |