Recursively solve the problem of frog jumping steps (Fibonacci sequence)

Topic: A frog can jump up one or two steps at a time. How many jumping methods are there for the frog to jump on an n-level step?

Answering Ideas
If there is only one step, then there is only one jumping method.
If there are two steps, then there are two jumping methods, one is to jump twice. Jump 1 level each time, and the other is to jump 2 levels at a time.
If the number of stages is greater than 2, set it to n. At this time, we regard the jumping method of n steps as a function of n, which is recorded as the first jump There are two different options: one is to jump one level for the first time, the number of jumps is equal to the number of jumps of the remaining n-1 steps, that is, the second is to jump two levels for the first time At this time, the number of jumping methods is equal to the number of jumping methods of the remaining n-2 steps, that is, the total number of different jumping methods of n steps is, and it can be seen that it is the
mathematical function of the Fibonacci sequence as follows

official

#include<stdio.h>
int ways(int n)
{
	if (n<=1)
	{
		return 1;
	}
	else
	{
		return ways(n-2) + ways(n - 1);
	}
}
int main()
{
	int n;
	scanf("%d", &n);
	printf("%d\n", ways(n));
	return 0;
}

If you modify the condition to skip one level at a time, you can also skip two levels, you can also skip three levels... can you also skip n levels?

Thinking
if the number of stages is n, then we regard the jumping method for n steps as a function of n, denoted as f(n), there are n different choices for the first jump: if it is the first time Jump one level, the number of jumps at this time is equal to the number of jumps for the remaining n-1 steps, which is f(n-1), if it is the first time to jump m (m<n), then jump The number of methods is equal to the number of jump methods of the remaining nm steps, that is, f(nm). If it is the first time to jump n steps, the number of jump methods is equal to 1. So
f(n)=f(n- 1)+f(n-2)+…f(nm)+…+f(2)+f(1)+1
so f(n-1)=f(n-2)+…+f(nm) +…f(2)+f(1)+1
Subtract the two formulas to get f(n)=2*f(n-1),
so the following result can be obtainedjieguo

Answer
If you modify the condition so that you can skip one level at a time, you can also skip 2 levels... or you can jump to n levels, thenjieguo

Guess you like

Origin blog.csdn.net/weixin_45796387/article/details/111213410