Leetcode 70. Climbing stairs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.