Lintcode Climbing Stairs

Source: Internet
Author: User
Tags lintcode

You is climbing a stair case. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In what many distinct ways can you climb to the top?

Example

Given An example n=3, 1+1+1=2+1=1+2=3

Return 3

For the problem, try-to-think about it on this.

Firstly, we define the problem of DP (n) as the ways of approaching to n stairs.

The problem of DP (n) depends on DP (N-1) and DP (N-2). Then the DP (n) = DP (N-1) + DP (n-2). Because there is a possibilities for DP (n) happen due to the rule that either it's accomplished by step 1 or Step 2 STA IRS before approaching to N.

Initialize the DP (0) =1 and DP (1) = 1.

Solve problem DP (n)

1  Public classSolution {2     /**3      * @paramN:an integer4      * @return: An integer5      */6      Public intClimbstairs (intN) {7         //Write your code here8         if(N <= 1) {9             return1;Ten         } One         intLast = 1, lastlast = 1; A         intnow = 0; -          for(inti = 1; I < n; i++) { -now = last +Lastlast; theLastlast =Last ; -Last =Now ; -         } -         returnNow ; +     } -}

Then this problem is a Fibonacci sequence

Lintcode 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.