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

不言
Release: 2023-04-04 09:50:02
forward
2764 people have browsed it


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
Copy after login
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);
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template