The C ++ implementation code of the Fibonacci series has an animal. Two days after birth, one animal begins to breed every day. How many animals will this animal have in 20th days? Suppose we only have one on the first day, so we cannot breed because it was born for only one day on the second day. In the third day, there were three animals in the first place, and so on. This is a typical recursive question. If you use a drawing or push it on your own every day, it is definitely a time-consuming task and may be wrong. At this time, our way of thinking should be like this. Please be careful: Today is the fifth day, the number of animals equals to the number of animals on the fourth day + the number of animals on the third day/* The number of animals generated on the third day is equal to the number on the fifth day */likewise: the number of animals on the third day is equal to the number of animals on the second day + the number of animals on the first day (new) the number of animals on the fourth day is equal to the number of animals on the third day + the number of animals on the second day (new) the number of animals in 20th days equals to the number of animals in 19th days + the number of animals in 18th days (new)
We can easily get a recursive law, F (n) = f (n-1) + f (n-2), and there is a condition that jumps out of recursion, that is, N> 20. Just find a language to implement the above recursion. The following is the code implementation of C ++:
We should focus on how to think about this question, because in the actual interview process, there was a variant of the Fibonacci number, in the test of a top 500 software companies, it requires less than one minute to make a similar question. This must be the thinking of a very good programmer. Work diligently and practice. You will surely get it!