Home  >  Article  >  Backend Development  >  How to solve the problem of frog jumping up steps in PHP (code)

How to solve the problem of frog jumping up steps in PHP (code)

不言
不言forward
2018-10-13 14:18:482714browse


The content of this article is about how PHP solves the problem of frogs jumping up steps (code). It has certain reference value. Friends in need can refer to it. I hope It will help you.

A frog can jump up 1 level or 2 steps at a time. Find out how many ways the frog can jump up an n-level step (different results will be calculated in different orders).

Ideas:

1. Find the rule f(1)=1 f(2)=2 f(3)=3 f(4)=5 f(n)=f(n -1) f(n-2) This is a Fibonacci sequence
2. Because when you adjust to the nth step, the first step from the bottom can be jumped in one step, and the second step from the bottom can also be jumped in one step. Skip over

Non-recursive version:

JumpFloor(target)
    if target==1 || target==2 return target
    jumpSum=0
    jump1=1
    jump2=2
    for i=3;i<target;i++
        jumpSum=jump1+jump2
        jump1=jump2
        jump2=jumpSum
    return jumpSum
function jumpFloor($number)
{
        if($number==1 || $number==2){
                return $number;
        }   
        $jumpSum=0;
        $jump1=1;
        $jump2=2;
        for($i=3;$i<=$number;$i++){
                $jumpSum=$jump1+$jump2;
                $jump1=$jump2;
                $jump2=$jumpSum;
        }   
        return $jumpSum;
}
$res=jumpFloor(10);
var_dump($res);

The above is the detailed content of How to solve the problem of frog jumping up steps in PHP (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete