Leetcode: 92 Climbing Stairs

Source: Internet
Author: User

Leetcode: 92 Climbing Stairs

You are climbing a stair case. It takes n steps 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?

A step has a total of n levels. If you can skip 1 level at a time, you can also skip 2 levels to find the total number of hops.

Analysis:

A maximum of two levels can be jumped at a time, then for the Level n (n> = 2) step, it is obvious that only n-1 jump level to arrive or from the level two jump from the level N-2 level to arrive, so as long as we know the n-1 level and the number of jump Method Of The N-2 level, the sum is the number of jump Method of the n level.

If the number of hops is f (n) and n is a step level, the following values are available:

F (n) = f (n-1) + f (n-2 ),

F (n) = 1 when n is 0, 1

The question is converted into a typical issue of the Fibonacci sequence.

Accepted Solution:

Class Solution {public: int climbStairs (int n) {int first = 1, second = 1; for (int I = 2; I <= n; I ++) {int temp = second; second = first + second; first = temp;} return second ;}};


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.