Monkey Climbing - Recursive Algorithm (detailed graphic and text)

Topic description

A monkey climbs and jumps on a hill with no more than 30 levels. The monkey can jump 1 level or 3 levels with one step up the mountain. Try to find out how many different climbing methods there are.

sample input

30

Sample output

58425

Problem solving ideas:

  1. First, find the recurrence relationship of f[k].
    Let n=30. The last step up the mountain reaches the 30th step. After completing the uphill, there are f[30] different climbing methods; at which level are you located before the 30th level? The first one is located at the 29th level (jump up 1 level to arrive), there are f[29] species; the second is at the 27th level (3 level jumps up), there are f[27] species; so there are:
    f[30]=f[29]+f[27]
    and so on, generally there is a recurrence relation:
    f[k]=f[k-1]+f[k-3] (k>3)
  2. Determine the initial conditions
    f[1]=1; ie 1=1
    f[2]=1; ie 2=1+1
    f[3]=2; ie 3=1+1+1; 3=3
  3. Implementation of recursion
    According to the above recursive relationship and initial conditions, set up a loop and apply recursion to find f[n].
    insert image description here

code section

#include<stdio.h>
long fun(int n)
{
    long key;
    if(n==1)
        key=1;
    else if(n==2)
        key=1;
    else if(n==3)
        key=2;
    else
        key=fun(n-1)+fun(n-3);
    return key;
}
int main()
{
    int m;
    long result;
    scanf("%d",&m);
    result=fun(m);
    printf("%ld",result);
    return 0;
}

The key to this question is to understand the recurrence relation in the question and solve it according to the recurrence relation and initial conditions.

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/106676243