Problem and deformation of frog jumping

Frog Jumping Step One

Problem description : A frog can jump up to 1 level or 2 at a time. Ask the frog to jump on an n-level step

How many jump methods are there in total (different order counts as different results)

如果n=1,只有一种跳法,那就是1
如果n=2,那么有两种跳法,2,[1,1]
如果n=3,那么有三种跳法,[1,1,1],,[1,2],[2,1]
如果n=4,那么有五种跳法,[1,1,1,1],[1,1,2],[1,2,1],[2,1,1],[2,2]
如果n=5,那么有八种跳法,[1,1,1,1,1],[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1],[2,2,1],[2,1,2],[1,2,2]
结果为1,2,3,5,8  这不正是斐波那契数列嘛

The problem is converted to solving the Fibonacci sequence. The following are the implementations of recursive and non-recursive functions.

Recursive solution

int jump(int n)
{
    
    
	if (n == 0 || n == 1 || n == 2)
		return n;
	else
	{
    
    
		return jump(n - 1) + jump(n - 2);
	}
}

Non-recursive solution

int jump(int n)
{
    
    
	if (n == 0 || n == 1 || n == 2)
	{
    
    
		return n;
	}
	int a = 1;
	int b = 2;
	int c = 3;
	while (n > 2)
	{
    
    
		c = a + b;
		a = b;
		b = c;
		n--;
	}
	return c;
}

Frog jumping two steps

Problem description : A frog can jump up to 1 level or 2 levels at a time...it can also jump to n levels. Beg the green

How many jumping methods are there to leapfrog on an n-level step?

问题分析:
f(n) = f(n-1) + f(n-2) + f(n-3) + … + f(n-(n-1)) + f(n-n)= f(0) + f(1) + f(2) + f(3) + … + f(n-2)+f(n-1)
f(n-1) = f(0) + f(1)+f(2)+f(3) + … + f((n-1)-1) = f(0) + f(1) + f(2) + f(3) + … + f(n-2)

so  f(n)=2*f(n-1)

Function implementation

int jump(int n)
{
    
    
	if (n == 0 || n == 1 || n == 2)
	{
    
    
		return n;
	}
	else
	{
    
    
		return 2 * jump(n - 1);
	}
}

Frog jumping three steps

Problem description : A frog can jump up to 1 level or 2 at a time... It can also jump to m level. Beg this

How many ways are there for a frog to jump on an n-level step?

Problem analysis :
f(n) = f(n-1) + f(n-2) + f(n-3) +… + f(nm)

f(n-1) = f(n-2) + f(n-3) + … + f(n-m) + f(n-m-1)

Simplified to get: f(n) = 2f(n-1)-f(nm-1)

Function implementation

int jump(int m,int n)
{
    
    
	if (n > m)
	{
    
    
		return 2 * jump(m, n - 1) - jump(m, n - m - 1);
	}
	// n <= m时跟问题二的解法相同
	else
	{
    
    
		if (n == 0 || n == 1 || n == 2)
		{
    
    
			return n;
		}
		else
		{
    
    
			return 2 * jump(m, n - 1);
		}
	}
}

Guess you like

Origin blog.csdn.net/DR5200/article/details/113058816