1、什么是递归

       编程语言中,函数Func(Type a,……)直接或间接调用函数本身,则该函数称为递归函数。在数学上,关于递归函数的定义如下:对于某一函数f(x),其定义域是集合A,那么若对于A集合中的某一个值X0,其函数值f(x0)由f(f(x0))决定,那么就称f(x)为递归函数。

         或者这么说递归递归是为了细分一个任务,将任务拆解成为一个有规律的,有相同解法的问题

 2、递归能解决什么问题

        最常见的额一类算法题目就是求斐波那契数列

    public static long factorial(long n){

        if(n==1){

            return 1;

        }

        return n*factorial(n-1);

   }

       类似这一类的问题,传统方法很难实现,但是通过递归很容易就能实现结果,但是递归程序有个很严重的问题,就是在程序执行中,递归其实就是不断调用自身,程序每次都会将一些变量和返回地址信息等压入栈中,这样在内存限定的情况下很容易发生内存溢出。还是完成后,还需要释放空间,在效率上也损耗极大。

        使用递归是一个非常有效的解决特定问题的途径,但是递归的局限性很让程序员很苦恼,随着程序语言的发展,慢慢的,一种解决递归内存占用的解决方案出现了。那就是尾递归,tail recursive。

3、尾递归

        当递归调用是整个函数体中最后执行的语句且它的返回值不属于表达式的一部分时,这个递归调用就是尾递归。尾递归函数的特点是在回归过程中不用做任何操作,递归结果可以直接返回。编译器在处理尾递归的时候,不会不听的创建栈帧,而是去覆盖之前的栈帧,《算法精解》里面的原话就是:"When a compiler detects a call that is tail recursive, it overwrites the current activation record instead of pushing a new one onto the stack.
        将上面的斐波那契数列方法改成尾递归,

    public static long factorial(long n,long a){

        if(n==1){

            return a;

        }

        return factorial(n-1, n*a);

    }

然而如果你认为尾递归就解决这个问题的话,就打错特错了。据了解,老牌程序语言在编译器里,并不支持尾递归的优化,所以即使你在这一类的程序语言里使用了尾递归,也不会得到想要的结果,比如,JAVA,C。等等大佬。

下面的例子让你更直观了解尾递归优化和递归的处理方式,这里我们选择了scala

def main(args: Array[String]): Unit = {
  val result = stackOverFlow(1)
  println(result)
}


/**
  * recursive
  *
  * @param o
  * @return
  */
def stackOverFlow(o: Int): Int = {
  val result = o + 1
  if (result < 100000) stackOverFlow(result)
  result
}

/**
  * tail recursive
  *
  * @param o
  * @return
  */
def tailStack(o: Int): Int = {
  val result = o + 1
  if (result > 100000)
    result
  else
    tailStack(result)

}

这里涉及了两个简单的方法,一个stackOverFlow方法(递归),一个tailStack方法(尾递归),当我们在调用stackOverFlow的时候,我们通过断点可以得到下面的界面:

递归与尾递归 recursive & tail recursive插图

 

这里我们可以,每次执行,都会记录一次栈帧,最终结果自然是:

Exception in thread "main" java.lang.StackOverflowError
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)
at demo4.RecursionDemo$.stackOverFlow(RecursionDemo.scala:19)

 

然后我们在运行 tailStack方法,我么会得到

递归与尾递归 recursive & tail recursive插图1

从上面的执行结果来看,我们可以看到每次执行并不会创建新的栈帧,而是复用了之前的栈帧。

我们将这个方法用java实现会发现:

递归与尾递归 recursive & tail recursive插图2

    这也就是为什么在scala里面可以使用尾递归,同样的程序,我们在使用java编写却会出现问题,原因就是我们上面所说的,现在的java编译器并不支持尾递归优化,而scala则支持了尾递归优化

 

331 对 “递归与尾递归 recursive & tail recursive”的想法;

  1. Pingback: brand name cialis
  2. Pingback: sildenafil canada
  3. I truly love your site.. Great colors & theme.

    Did you develop this amazing site yourself?
    Please reply back as I’m attempting to create my very own website and would love to know where you got
    this from or just what the theme is named. Appreciate it!

  4. I have been surfing online more than 2 hours today, yet
    I never found any interesting article like yours. It’s
    pretty worth enough for me. In my opinion, if all site owners
    and bloggers made good content as you did, the net will be much more useful than ever before.

  5. It’s tthe est tike to mke a feew plans ffor thhe lonjg runn
    and it’s timne tto bbe happy. I hae lean this submit and if Ickuld
    I desiree too recommed yoou some fasinating iswsues orr suggestions.
    Perhaps youu can wrife next articles relpating too thi article.
    I want to leazrn even more thinfs about it!

  6. One thing is one of the most typical incentives for making use of your cards is a cash-back and also rebate offer. Generally, you’ll have access to 1-5 back on various buying. Depending on the credit cards, you may get 1 returning on most purchases, and 5 in return on expenses made going to convenience stores, filling stations, grocery stores along with ‘member merchants’.

  7. He gօes to sleep early, yеs I children you not. Hᥱ from the Boisy Doisy Hot Shoe
    Shuffle and Berry Ⲥlub Ꮪhake, ups stumps well prior to midnight and takes themsᥱlves to bedroom.
    We were all іn such shoc ouг company had to acquire yet anothеr draft beer to soothe our
    nerves.

  8. It’s appropriate time to make some plans for the future and it’s
    time to be happy. I’ve read this post and if I could
    I desire to suggest you few interesting things or
    advice. Perhaps you can write next articles referring to this
    article. I wish to read more things about it!

  9. Hey there would you mind sharing which blog platform you’re working with?

    I’m going to start my own blog in the near future but I’m having
    a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most
    blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had to ask!

  10. It’s appropriate time to make a few plans for the long run and
    it is time to be happy. I have learn this post and if I may just I wish to counsel you few attention-grabbing things or advice.
    Perhaps you can write next articles referring to this article.
    I wish to learn even more things approximately it!

  11. Hey! This is kind of off topic but I need some guidance from an established blog.

    Is it difficult to set up your own blog? I’m not
    very techincal but I can figure things out pretty fast.
    I’m thinking about setting up my own but I’m not sure where to start.
    Do you have any ideas or suggestions? With thanks
    cheap football jerseys

  12. Wе provіde the widest assortment from unique and gorgeous
    bаby room household furniture as weⅼl as kid’s furniture.
    Our home furniture has actualⅼy been actuaⅼly helped
    make by several of one of the most special designers іn Europe and also products feаture
    craɗles, сots, cotbeds, changing dining tables, trunk from drɑwers, wаrdrobes, Ƅaby roоm benches, younger beds, singjlar bedrοomѕ bunk beds, the middle of surge mattress, high rise mattress, 8
    banner bedroomѕ, bed linen, lighting, rugѕ, higher armchairs, child
    loungers, tгavel units, child seat, wooden toys and also a lot so much more …

  13. Hi there! This is kind of off topic but I need some help from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal but
    I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure where to begin. Do you
    have any points or suggestions? Cheers

  14. It is the best time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I want to suggest you few interesting things or tips.
    Perhaps you could write next articles referring to this article.
    I want to read even more things about it!

  15. One thing I want to say is the fact that car insurance cancellations is a horrible experience and if you are doing the appropriate things being a driver you simply won’t get one. A lot of people do are sent the notice that they have been officially dropped by their particular insurance company they have to scramble to get extra insurance after the cancellation. Cheap auto insurance rates are often hard to get after a cancellation. Knowing the main reasons for auto insurance canceling can help people prevent getting rid of in one of the most critical privileges out there. Thanks for the strategies shared through your blog.

  16. It’s the best time to make some plans for the long run and it is time to be happy.
    I have read this put up and if I may I desire to suggest you few attention-grabbing things or suggestions.
    Maybe you can write next articles relating
    to this article. I want to read even more things about it!

  17. I have seen that currently, more and more people are attracted to cams and the discipline of pictures. However, being photographer, you should first expend so much period deciding which model of camera to buy plus moving store to store just so you could potentially buy the least expensive camera of the trademark you have decided to pick. But it won’t end there. You also have to contemplate whether you should buy a digital digicam extended warranty. Thanks alot : ) for the good recommendations I acquired from your weblog.

  18. Hello would you mind letting me know which webhost you’re utilizing?
    I’ve loaded your blog in 3 different browsers and I must
    say this blog loads a lot faster then most. Can you suggest a
    good web hosting provider at a reasonable price?
    Thank you, I appreciate it!

  19. It is appropriate time to make a few plans for the long run and it is
    time to be happy. I have learn this post and if I may just I desire to recommend you
    few fascinating things or tips. Perhaps you could write next articles regarding
    this article. I wish to read even more things
    approximately it!

  20. Pingback: voltaren
  21. Pingback: finasteride nz
  22. ouг teɑm possess one all over DЅs door and also
    at the top and also bottom fгom the stairs and also across the door to the kitchen area he is actually not so negative now (he’s 4.8) yet when he initially acquired
    active he felt like brightening and also that juѕt made
    my lifestyle a lоt easier. I am actuaⅼly pretty certain that he could possibly shake off it if he was truly enthusiastic
    yet rᥱgarding I’m anxious, that’s the same as having him in a cot that is actually
    simply the whole ѕpace!

  23. Pingback: buy viagra online
  24. I have been surfing online more than 3 hours today, yet I never
    found any interesting article like yours. It is pretty worth enough for me.
    In my opinion, if all site owners and bloggers made good content as you did, the web will be a lot more useful than ever before.

  25. Have you ever thought about writing an ebook or guest authoring on other websites?
    I have a blog based upon on the same subjects you discuss and
    would love to have you share some stories/information. I know my audience would
    appreciate your work. If you’re even remotely interested, feel free to shoot me an e mail.

  26. I simply couldn’t go away your web site prior to suggesting that I really
    loved the standard info a person provide for your
    visitors? Is going to be again ceaselessly to investigate cross-check
    new posts

  27. Its such as you learn my mind! You seem to know so much approximately this, such as you wrote the book in it or something.
    I believe that you can do with a few % to pressure the message house a bit,
    but other than that, this is great blog. An excellent read.

    I’ll certainly be back.

  28. It is perfect time to make a few plans for the future and it
    is time to be happy. I have read this put up and
    if I may I want to suggest you some attention-grabbing issues or suggestions.
    Perhaps you can write next articles regarding this article.
    I want to read more issues approximately it!

  29. Pingback: aricept 5 mg
  30. Thanks for the ideas shared in your blog. Something also important I would like to talk about is that weight-loss is not all about going on a fad diet and trying to reduce as much weight as you’re able in a couple of days. The most effective way to lose weight is by consuming it gradually and obeying some basic suggestions which can allow you to make the most from a attempt to lose weight. You may know and be following some of these tips, but reinforcing expertise never damages.

  31. Pingback: buy sildenafil
  32. Pingback: cialis for sale
  33. Pingback: cialis review
  34. Pingback: sildenafil tadalafil
  35. Pingback: viagra generic
  36. Pingback: sildenafil medicine
  37. Pingback: sildenafil 100mg usa
  38. Pingback: viagra best price
  39. I have been browsing on-line more than three hours
    nowadays, yet I by no means found any interesting article like yours.
    It is beautiful value sufficient for me. Personally, if all website owners and bloggers made
    just right content material as you did, the web shall be a
    lot more helpful than ever before.

  40. Hey there would you mind sharing which blog platform you’re using?
    I’m going to start my own blog in the near future but I’m
    having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique.

    P.S Sorry for getting off-topic but I had to ask!

  41. Wikipedia inherited and also welcomed the social assumptions
    that an encyclopedia should certainly be reliable, detailed,
    and also underpinned by thee logical spirit of the Knowledge However iit threw out centuries of accepted approaches for acquiring that.

  42. It is perfect time to make some plans for the future and it
    is time to be happy. I’ve read this post and if I could I want to suggest
    you some interesting things or suggestions. Perhaps you could write next articles referring to this article.
    I want to read even more things about it!

  43. Hi! Someone in my Myspace group shared this site with us so I came to look it over.
    I’m definitely enjoying the information. I’m book-marking and will
    be tweeting this to my followers! Fantastic blog and excellent design.

  44. I have been browsing on-line greater than 3 hours as of
    late, yet I by no means discovered any interesting article like yours.
    It is pretty value enough for me. In my view, if all webmasters and bloggers
    made good content as you did, the web shall be a lot more useful than ever before.

  45. Pingback: finasteride 1mg cost
  46. It’s the best time to make some plans for the long
    run and it is time to be happy. I have learn this submit and if I may just I want to counsel you some interesting issues
    or suggestions. Perhaps you can write subsequent articles regarding this article.
    I desire to learn more things about it!

  47. Pingback: motilium pill
  48. Pingback: naltrexone dosage 6mg
  49. Hi! I could have sworn I’ve visited this blog before but after looking at some of the articles I realized it’s
    new to me. Anyhow, I’m certainly pleased
    I stumbled upon it and I’ll be book-marking
    it and checking back often!

  50. Hi, I do think this is a great website. I stumbledupon it 😉
    I am going to revisit yet again since i have saved as a favorite it.
    Money and freedom is the greatest way to change, may you
    be rich and continue to help other people.

  51. Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective.
    A lot of times it’s very hard to get that “perfect balance” between usability and visual appeal.
    I must say you’ve done a awesome job with this. Also, the blog
    loads very fast for me on Firefox. Superb Blog!

  52. Hello! Someone in my Myspace group shared this site with us so
    I came to take a look. I’m definitely enjoying the
    information. I’m book-marking and will be tweeting this to my followers!
    Superb blog and outstanding design.

  53. Pingback: tadalafil 100mg
  54. Pingback: sildenafil capsule
  55. Pingback: viagra by mail
  56. Woah! I’m really digging the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between user friendliness and
    visual appeal. I must say that you’ve done a very good job with this.
    Additionally, the blog loads very fast for me on Internet explorer.
    Exceptional Blog!

  57. Pingback: viagra coupon
  58. Pingback: generic viagra
  59. Pingback: order viagra online
  60. Pingback: viagra pills

发表评论