Fortune Telling Collection - Horoscope - What is the reason why recursive algorithm is particularly slow?
What is the reason why recursive algorithm is particularly slow?
But in practice, we will find that the recursive processing of some problems, especially recursive problems, will show extremely low efficiency. This problem occurs because of repeated calculation.
For example, using recursion to solve the nth term of Fibonacci sequence, the general recursion formula is
f(n) = f(n- 1)+f(n-2)
f(2) = 1
f( 1) = 1
Please try to simulate the computer running this recursion, and you will find that one of the terms f(x) is calculated more than once. When you calculate f(5), you will try to calculate f(4) and f(3), but when you calculate f(4), you actually have to calculate f(3), so that f(3) is called twice.
Imagine that this process is exponentially expanding, and the efficiency will drop rapidly with the increase of n.
To solve this problem, we can use the idea of rote learning.
Define the memory array r and change the function body to:
Definition f(n):
If r[n] is defined, just return r[n] as the answer.
Otherwise, f(n) = f(n- 1)+f(n-2).
Before returning the value, write it down in r[n].
The efficiency of the improved recursive function is almost the same as that of the recursive algorithm.
- Related articles
- Are there any good childhood romance novels?
- How to deal with Leo's indifference?
- Four constellations that are brave and weak and don't care about face.
- What constellation is most likely to have the characteristics of all constellations?
- Twelve constellations cotton doll blind box _ twelve constellations exclusive cotton candy
- Do you like good girls and don't like constellation men who love to play with girls?
- Is Pisces the most hesitant constellation in 12?
- What constellation does Libra match? The fastest constellation to match Libra.
- 1994 Lunar June 1 1 What is the birthday sign?
- Four constellations that don't change their personalities often.