Stair climbing--recursive and function self-invocation algorithm

Source: Internet
Author: User

Title Description Description

The tree teacher climbed the stairs, he can walk 1 or 2 levels, enter the number of stairs, to find different ways to go
For example: The staircase has a total of 3 levels, he can go one level at a time, or the first step, the second walk two levels
Can also be the first time to go two levels, the second step, a total of 3 methods. input/output format input/output Input Format:
The input contains several rows, each containing a positive integer N, representing the stair series, 1 <= N <= 30
output Format:
Different walk count, each line input corresponding line output input and Output sample sample Input/output sample Test point # #

Input Sample:

5

8

10

Sample output:

8

34

89

Ideas:

Use enumerations to abstract out general expressions:

When N=0, f (n) =1

N=1,f (n) =1

N=2,f (n) =2

N=3,fn=3

N=4,fn=5

F (2) =f (1) +f (0)

F (3) =f (2) +f (1)

F (4) =f (3) +f (2)

.......

From the above analysis can be summed up the general expression:f (n) =f (n-2) +f (n-1)

So the problem is the transformed Fibonacci sequence!

The code is as follows:

1#include <stdio.h>2 intDfsintN)3 {4     if(n<3)//if it is 1 or 2, there are 1, 2 methods to return directly.5     {6         returnN;7     }8     Else//otherwise, recursion! 9     {Ten         returnDFS (N-1) +dfs (n2);//use a general expression to solve (in fact, the Fibonacci sequence) One     }     A } - intMain () - { the     intN; -scanf"%d",&n); -printf"%d\n", DFS (n)); -     return 0; +}

Stair climbing--recursive and function self-invocation algorithm

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.