Tail Recursion尾遞歸

什么是尾遞歸

Tail Recursion /te?l r??k??r?n/

In traditional recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don’t get the result of your calculation until you have returned from every recursive call.

In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)). Basically, the return value of any given recursive step is the same as the return value of the next recursive call.

示例一 : 累加

Consider a simple function that adds the first N integers. (e.g. sum(5) = 1 + 2 + 3 + 4 + 5 = 15).

Here is a simple JavaScript implementation that uses recursion:

function recsum(x) {if (x === 1) {return x;} else {return x + recsum(x - 1);}
}

If you called recsum(5), this is what the JavaScript interpreter would evaluate:

recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + 1)))
15

Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.

Here’s a tail-recursive version of the same function:

function tailrecsum(x, running_total = 0) {if (x === 0) {return running_total;} else {return tailrecsum(x - 1, running_total + x);}
}

Here’s the sequence of events that would occur if you called tailrecsum(5), (which would effectively be tailrecsum(5, 0), because of the default second argument).

tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15

In the tail-recursive case, with each evaluation of the recursive call, the running_total is updated.

示例二 : 斐波那契數列##

在數學上,斐波那契數列以如下被以遞推的方法定義:F(1)=1,F(2)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 3,n ∈ N*)。

換成Java代碼如下:

public static long classicFibonacci(long num) {if(num <= 0) {return 0;}else if(num == 1 || num == 2) {return 1;}else {return classicFibonacci(num - 1) + classicFibonacci(num - 2);}
}

用尾遞歸方法改造一下

public static long tailRecursionFibonacci(long num) {if(num <= 0) {return 0;}else if(num == 1 || num == 2) {return 1;}else {return tailRecursionFibonacci(num, 1, 1, 2);}
}public static long tailRecursionFibonacci(long num, long first, long second, long index) {if(num == index) {return second;}else {return tailRecursionFibonacci(num, second, first + second, index + 1);//尾遞歸調用}
}

為什么需要尾遞歸

因為性能。

The consequence of tail recursion is that once you are ready to perform your next recursive step, you don’t need the current stack frame any more. This allows for some optimization. In fact, with an appropriately written compiler, you should never have a stack overflow snicker with a tail recursive call. Simply reuse the current stack frame for the next recursive step.

那么,我們不妨測試一下示例二:斐波那契數列中兩種算法。測試方法是用兩種算法得出斐波那契數列的第46項是多少且分別消耗多長時間。

首先,用classicFibonacci計算得出斐波那契數列的第46項。

@Test
public void testClassicFibonacci() {System.out.println(classicFibonacci(46));
}

運行結果如下

斐波那契數列的第46項是1836311903,用classicFibonacci得出斐波那契數列的第46項所消耗的時間是43.026秒


接著,用有尾遞歸方式tailRecursionFibonacci計算得出斐波那契數列的第46項。

@Test
public void testTailRecursionFibonacci() {System.out.println(tailRecursionFibonacci(46));
}

斐波那契數列的第46項是1836311903,跟classicFibonacci的一致。用有尾遞歸方式的tailRecursionFibonacci得出斐波那契數列的第46項所消耗的時間是0.035秒,是classicFibonacci的1229倍,差距懸殊。

如果繼續用classicFibonacci得出斐波那契數列第n項(n>46),將消耗更長時間,甚至天荒地老也沒有算完。

參考資料

  1. What is tail recursion?
  2. 斐波那契數列

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/445958.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/445958.shtml
英文地址,請注明出處:http://en.pswp.cn/news/445958.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python遞歸算法案例教案_python教案

第五單元進階程序設計(總10課時)第一節選擇編程語言(1課時)一、教學目標1、了解程序設計語言和兩種翻譯方式&#xff1b;2、了解Python背景、功能、安裝&#xff0c;熟悉Python編程環境&#xff1b;3、編程初體驗。體驗一個小程序從建立、輸入、調試、運行、保存的全過程。掌握…

FFmpeg源代碼簡單分析-解碼-av_read_frame()

參考鏈接 ffmpeg 源代碼簡單分析 &#xff1a; av_read_frame()_雷霄驊的博客-CSDN博客_ffmpeg frame av_read_frame() ffmpeg中的av_read_frame()的作用是讀取碼流中的音頻若干幀或者視頻一幀。例如&#xff0c;解碼視頻的時候&#xff0c;每解碼一個視頻幀&#xff0c;需要…

數據庫 流量切分_私域流量之社群運營技巧,社群運營技巧解析

一、明白社群運營的目的1、社群的目的確立任何一個社群(組織)成立的時分&#xff0c;都是承載著一定的目的的&#xff0c;這個目的就像是北極星一樣&#xff0c;指引著我們的方向。確立運營目的的過程&#xff0c;也是在尋覓北極星的過程。社群運營屬于觸達用戶的一種方式&…

用Python在Tomcat成功啟動后自動打開瀏覽器訪問Web應用

前提條件 WindowsPython 2.7需設置CATALINA_HOME環境變量 放碼過來 # -*- coding: utf-8 -* import os import time import subprocesstomcatStartFilePath C:\\tomcat\\apache-tomcat-7.0.90-windows-x64\\apache-tomcat-7.0.90\\bin\\startup.bat browserPath C:\\Users…

FFmpeg源代碼簡單分析-解碼-avcodec_send_packet 和 avcodec_receive_frame 替代 avcodec_decode_video2

參考鏈接 ffmpeg 源代碼簡單分析 &#xff1a; avcodec_decode_video2()_雷霄驊的博客-CSDN博客_avcodec_decode_video2 avcodec_decode_video2 ffmpeg中的avcodec_decode_video2()的作用是解碼一幀視頻數據。輸入一個壓縮編碼的結構體AVPacket&#xff0c;輸出一個解碼后的結…

FFmpeg源代碼簡單分析-解碼-avformat_close_input()

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;avformat_close_input()_雷霄驊的博客-CSDN博客_avformat_close_input avformat_close_input() 本文簡單分析FFmpeg的avformat_close_input()函數。該函數用于關閉一個AVFormatContext&#xff0c;一般情況下是和avformat_open_inp…

android 使用shell模擬觸屏_[Android]通過adb shell input上報命令模擬屏幕點擊事件【轉】...

常用的 input上報命令&#xff1a;input text 1234 實際向界面注入1234文字&#xff0c;有輸入框&#xff0c;能明顯看到效果input keyevent 4 鍵盤事件&#xff0c;4 為返回input tap 100 300 單擊觸屏事件 &#xff0c;模擬點擊x100 y 300 位置input swipe 100 300 500 300 …

用Python連接MySQL并進行CRUD

Tag: MySQL, PyMySQL, Python 準備條件 Python 2.7MySQL 5.5安裝 PyMySQL pip install PyMySQL 放碼過來 創建一數據表 CREATE TABLE users (id int(11) NOT NULL AUTO_INCREMENT,email varchar(255) COLLATE utf8_bin NOT NULL,password varchar(255) COLLATE utf8_bin N…

python網絡爬蟲的方法有幾種_Python網絡爬蟲過程中5種網頁去重方法簡要介紹

一般的&#xff0c;我們想抓取一個網站所有的URL&#xff0c;首先通過起始URL&#xff0c;之后通過網絡爬蟲提取出該網頁中所有的URL鏈接&#xff0c;之后再對提取出來的每個URL進行爬取&#xff0c;提取出各個網頁中的新一輪URL&#xff0c;以此類推。整體的感覺就是自上而下進…

FFmpeg源代碼簡單分析-編碼-avformat_alloc_output_context2()

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;avformat_alloc_output_context2()_雷霄驊的博客-CSDN博客_avformat_alloc_context avformat_alloc_output_context2() 在基于FFmpeg的視音頻編碼器程序中&#xff0c;該函數通常是第一個調用的函數&#xff08;除了組件注冊函數av…

《深入理解JVM.2nd》筆記(一):走進Java

概述 Java技術體系 Java程序設計語言各種硬件平臺上的Java虛擬機Class文件格式Java API類庫來自商業機構和開源社區的第三方Java類庫 Java發展史 Java虛擬機發展史 展望Java技術的未來 模塊化 混合語言 多核并行 進一步豐富語法 64位虛擬機 實戰&#xff1a;自己編譯…

js監聽只讀文本框_js 動態控制 input 框 的只讀屬性

input 框的只讀屬性&#xff1a; readonly在頁面中直接添加為只讀時&#xff0c;可在input中直接添加 readonly"readonly"&#xff0c;但是如果想通過點擊按鈕來改變的話&#xff0c;需要通過js(或jquery)來實現。最近一次使用這個&#xff0c;終于發現了以前寫這…

FFmpeg源代碼簡單分析-編碼-avformat_write_header()

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;avformat_write_header()_雷霄驊的博客-CSDN博客_avformat_write_header avformat_write_header() FFmpeg寫文件用到的3個函數&#xff1a;avformat_write_header()&#xff0c;av_write_frame()以及av_write_trailer()其中av_writ…

《深入理解JVM.2nd》筆記(二):Java內存區域與內存溢出異常

文章目錄概述運行時數據區域程序計數器Java虛擬機棧本地方法棧Java堆方法區運行時常量池直接內存HotSpot虛擬機對象探秘對象的創建第一步第二步第三步第四步最后一腳對象的內存布局對象頭Header第一部分第二部分實例數據Instance對齊填充Padding對象的訪問定位句柄直接指針對象…

vue底部選擇器_Vue組件-極簡的地址選擇器

一、前言本文用Vue完成一個極簡的地點選擇器&#xff0c;我們接下來帶大家實現這個。當然其中也有一些值得學習與注意的地方。話不多說&#xff0c;我們先上demo圖。因為每個人的需要不一樣&#xff0c;我這邊就不在實現更多的功能&#xff0c;所以留有更大的空間供大家增刪改。…

FFmpeg源代碼簡單分析-編碼-avcodec_encode_video()已被send_frame 和 receive_packet替代

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;avcodec_encode_video()_雷霄驊的博客-CSDN博客_avcodec_encode_video2 avcodec_encode_video() 該函數用于編碼一幀視頻數據。函數已被棄用參考鏈接&#xff1a;FFmpeg 新舊版本編碼 API 的區別_zouzhiheng的博客-CSDN博客 send_f…

《深入理解JVM.2nd》筆記(三):垃圾收集器與垃圾回收策略

文章目錄概述對象已死嗎引用計數算法可達性分析算法再談引用finalize()&#xff1a;生存還是死亡回收方法區垃圾收集算法標記-清除算法復制算法標記-整理算法分代收集算法HotSpot的算法實現枚舉根結點安全點安全區域垃圾收集器SerialParNewParallel ScavengeSerial OldParallel…

python計算股票趨勢_通過機器學習的線性回歸算法預測股票走勢(用Python實現)...

1 波士頓房價數據分析安裝好Python的Sklearn庫后&#xff0c;在安裝包下的路徑中就能看到描述波士頓房價的csv文件&#xff0c;具體路徑是“python安裝路徑\Lib\site-packages\sklearn\datasets\data”&#xff0c;在這個目錄中還包含了Sklearn庫會用到的其他數據文件&#xff…

FFmpeg源代碼簡單分析-編碼-av_write_frame()

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;av_write_frame()_雷霄驊的博客-CSDN博客_av_write_frame av_write_frame() av_write_frame()用于輸出一幀視音頻數據&#xff0c;它的聲明位于libavformat\avformat.h&#xff0c;如下所示。 /*** Write a packet to an output me…

《深入理解JVM.2nd》筆記(四):虛擬機性能監控與故障處理工具

文章目錄概述JDK的命令行工具jps&#xff1a;虛擬機進程狀況工具jstat&#xff1a;虛擬機統計信息監視工具jinfo&#xff1a;Java配置信息工具jmap&#xff1a;Java內存映像工具jhat&#xff1a;虛擬機堆轉儲快照分析工具jstack&#xff1a;Java堆棧跟蹤工具HSDIS&#xff1a;J…