Recursively solving this problem: a small doe doe students a year from the age of four, press law, only the first n number of females?


>> casually tease tease
students who have no problem holding a recursive thinking big head? Many books only introduces the concept and operation of recursive logic, it does not tell us how to solve these problems quickly and efficiently, and more inadequate, please correct me.

Analysis >>
1. Recursive Thinking: From outside to inside, from the branch to the roots, from 1 to n.
2. find the parameter: This parameter whole series recursive all layers, here is obvious: n-
3. Law found: each one or more inner layers thereto a linkage between (or within a certain inner layer ...): Here the change in the number of rabbits per year and n do a comparison table to find the law. When did the idea to put each neatly enumerated, the law of nature presented.

>> Solution
1 include:
F (n) corresponding to the n represents the total number of rabbits
and n represents Yearly, a first year [4] had a rabbit years [0] year-old baby, so that f (1 ) = 2
number in parentheses represents the number of rabbits, the internal digital representation of age

 

2. Comparison:

The first four years as arithmetic;
second four-year difference is increasing every year, but the difference is the difference between the incremental value of the first four years;
a third four-year difference in increments faster every year, the difference the second increment value equal to four years.

3. Substitution:
with front Rabbit number f () be represented by a combination of the last f (), then the second column expression with
FIG from left to right of substitution
obtained: f (n) = f ( n - 1) + f (n - 4 ), perfect recursive function, so everybody with a good school mathematics!
This document is a table

4.C ++ Code:

#include<iostream>
using namespace std;

int func( int a )
{
    return a <= 4 ? ( a + 1 ) : func ( a - 1 ) + func ( a - 4 ) ;
}
int main ()
{
    int n;
    cout << " Please enter a number: " ;
    cin>>n;
    cout<<""<<n<<"年有"<<func(n)<<"只兔子"<<endl;
    return 0;
}

 

----------------
Disclaimer: This article is CSDN blogger "DDman & amp;" in the original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source and this link statement.
Original link: https: //blog.csdn.net/weixin_45398308/article/details/102989242

Guess you like

Origin www.cnblogs.com/huigebj/p/12442851.html