Fibonacci with Memo
PHP
Medium
5 views
Problem Description
Compute fib(n) with memoization (fib(0)=0, fib(1)=1).
Input Format
One integer n.
Output Format
One integer.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$n=intval($inputText);
$memo=[0=>0,1=>1];
function fib($n,&$memo){
if(isset($memo[$n])) return $memo[$n];
$memo[$n]=fib($n-1,$memo)+fib($n-2,$memo);
return $memo[$n];
}
echo fib($n,$memo);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!