Leetcode: climbing_stairs

Source: Internet
Author: User

I. Question

There are n steps to climb the stairs. Each time you can climb the level 1 or Level 2, how many crawling methods do you climb to the top?

Ii. Analysis

If F (n) is set, it indicates the number of different methods used to climb the n-level stair. to climb the n-level stair, there are two options:

1. Step forward from n-1

2. Two steps forward from The N-2 order

So there is, F (n) = f (n-1) + f (n-2) Isn't that the Fibonacci series?

Therefore,

Method 1: Iteration

Method 2: Recursion

Method 3: formula F (n) = (1/√ 5) * {[(1 + √ 5)/2] ^ N-[(1-√ 5) /2] ^ n}


Class solution {public: int climbstairs (int n) {int flag; int stair0 = 1; int stair1 = 1; if (n <= 0) return 0; if (n = 1) return 1; for (INT I = 2; I <= N; I ++) {flag = stair1; stair1 = stair0 + stair1; stair0 = flag;} return stair1 ;}}; formula: Class solution {public: int climbstairs (int n) {double flag = SQRT (5 ); return floor (POW (1 + flag)/2, n + 1) + POW (1-flag)/2, n + 1 )) /flag + 0.5 );}};


Leetcode: 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.