Analysis
Easy to use
Source
Https://leetcode.com/problems/climbing-stairs/
Question
You are climbing a stair case. It takesNSteps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note:GivenNWill be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 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
Answer
Runtime: 2 MS, faster than 100.00% of Java online submissions for climbing stairs.
1 package leetcode; 2 3 Public class l70_climbingstairs {4 // steps of the stairs equals to: 5 // ways (n) = ways (n-1) + ways (n-2) 6 Public int climbstairs (int n) {7 int pre1 = 0, pre2 = 1, ways = 0; // number of steps before two steps, number of steps before One Step 8 If (n <= 0) {9 return N; 10} 11 for (INT I = 1; I <= N; I ++) 12 {13 ways = pre1 + pre2; 14 pre1 = pre2; 15 pre2 = ways; 16} 17 return ways; 18} 19}
Leetcode 70. Climbing stairs