# Leetcode "climbing stairs"

Source: Internet
Author: User

The best way to learn DP from DFS! Nice problem.

My intuition is that it can be solved by DFS:

`class Solution {public:        int climbStairs(int n) {        if (n == 0) return 1;        int cnt0 = climbStairs(n - 1);        int cnt1 = 0;        if(n >= 2) cnt1 = climbStairs(n - 2);        return cnt0 + cnt1;    }};`

You can get correct answer by this, but it is taking too long-tle.

Actually, the equation is quite obvious in abve code: s [N] = s [n-1] + s [N-2] With s [1] = 1; s [2] = 2. sooooo beautiful:

`class Solution {public:        int climbStairs(int n) {        if (n == 0) return 0;        if (n == 1) return 1;        if (n == 2) return 2;        //    S[n] = S[n-1] + S[n-2]; S[1] = 1; S[2] = 2        int ret = 0;        int *s = new int[n + 1];        s[1] = 1; s[2] = 2;        for (int i = 3; i <= n; i++)        {            s[i] = s[i - 1] + s[i - 2];        }        ret = s[n];        delete[] s;        return ret;    }};`
Related Keywords:

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.