iT邦幫忙

0

Recursion

接下來我們要來學習很重要的遞迴,接下來讓我們了解吧

  • 函式呼叫自己
  • 使用到Stack

Fibonacci

https://ithelp.ithome.com.tw/upload/images/20210517/20130419BLam20M9qV.png

function Recursion(n){
    if(n==0){ 
        return 0 
    }else if(n==1){
        return 1
    }
    else{
        return Recursion(n-2) + Recursion(n-1)  
    }
}

for(let i = 0 ; i <= 10; i++){
    console.log(Recursion(i))
}
//0
1
1
2
3
5
8
13
21
34
55

For迴圈

也可以使用Loop執行

function Fibonacci(n){
    let result = []
    result[0] = 0
    result[1] = 1
    for(let i=2; i <= n; i++){
        result[i] = result[i-1] + result[i-2]
    }
    return result
}

console.log(Fibonacci(10))
//[
    0, 1,  1,  2,  3,
    5, 8, 13, 21, 34,
   55
 ]

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言