Climbing stairs stair climb problem, each time can take 1 or 2 steps, climb the n-layer stair total method (disguised fiber nacci)

Source: Internet
Author: User

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?

When n = 1, there is one method, that is, take one step directly.

When n = 2, there are two methods: two steps in a row or two steps in a row.

For N, if F (n) is set to the total method, F (n) = f (n-1) + f (n-2)

PS: F (n-1) is the first step,

F (n-2) is the first two steps

Solution to the back-to-fiber nacci problem:

 1 class Solution { 2 public: 3     int climbStairs(int n) { 4         if(n < 0) 5             return -1; 6         int res[] = {0,1}; 7         if(n<2) 8             return res[n]; 9             10         int fib1 = 0;11         int fib2 = 1;12         13         int result = 1;14         15         for(int i = 1 ; i <= n ; i++){16             result = fib1 + fib2;17             fib1 = fib2;18             fib2 = result;19         }20         21         return result;22     }23 };

 

Climbing stairs stair climb problem, each time can take 1 or 2 steps, climb the n-layer stair total method (disguised fiber nacci)

Related Article

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.