Slag with a brush Leetcode0070 you learn to climb stairs

Title Description

Suppose you are climbing stairs. N order you need to get to the roof.

Every time you can climb one or two steps. How many different ways can climb to the roof of it?

Note: Given n is a positive integer.

Example 1:

Input: 2
Output: 2
explanation: There are two methods can climb the roof.
1.1 + 1-order-order
2.2 Order
Example 2:

Input: 3
Output: 3
Explanation: There are three methods can climb to the roof.
1.1 + 1 order + 1-order-order
2.1 + 2-order order
3.2 + 1-order-order

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/climbing-stairs
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Vernacular Title:

Limited ability to be able to go upstairs once one step or two steps, and asked how much the total order n method steps have?

algorithm:

How many kinds of programs many ancient scientists prefer to manually calculate this, the recursive Ye Hao achieve, go one step, look at the rest of the n-1 needs; go 2 steps, look at the remaining n-2 Ge how many kinds of programs need.

Here I intend by this problem, but also be analyzed from simple to hard look at DP (dynamic programming) dynamic programming algorithm it

Take a look at the i-th step of the walk and which are directly related. 

Only the i-th step i-1 and the first order, is directly related to the number of i-2 order.

dp

0

1

2

3

4

5

6

 

0

1

2

3

5

8

13

 

dp[i]=dp[i-2]+dp[i-1];

C language code is complete

#include <stdio.h>
#include <stdlib.h>
int climbStairs(int n)
{
    if(n<0)  return 0;
    if(n<=2) return n;
    int dp[n+1];  //

    dp[0]=0;
    dp[1]=1;
    dp[2]=2;
    int i=3;
    for(i=3; i<=n; i++)
    {
        dp[i]=dp[i-1]+dp[i-2];
    }
    return dp[n];
}

int main()
{
    int n;
    scanf("%d",&n);
    int result=climbStairs(n);
    printf("%d\n",result);
    return 0;
}

 

Published 16 original articles · won praise 2 · Views 2250

Guess you like

Origin blog.csdn.net/qq_39729096/article/details/105284763