Algorithm--Recursive strategy

Source: Internet
Author: User

This article address:, reprint please indicate source address.

Recursive method is an important mathematical method, which is widely used in all fields of mathematics, and is also an important algorithm for computer numerical calculation. This algorithm is characterized by: a problem of the solution needs a series of calculations, between the known conditions and the problem there is always a link between the relationship, in the calculation, if you can find the relationship between the number of pre-and post-process (that is, recursive), then from the problem gradually pushed to the known conditions, this method is called inverse push. Whether push or reverse, the key is to find a recursive type. This method of dealing with the problem can make the complex operation into a number of repetitive simple operations, and give full play to the characteristics of the computer is good at repeating processing.

  The first problem of recursive algorithm is to get the relationship between adjacent data items (that is, recursive relationship). The recursive algorithm avoids the trouble of solving the formula of the general term, and decomposes a complex problem into a sequential simple operation. in general, recursive methods can be considered as a special iterative algorithm.

Example: Fibonacci series

The problem of Fibonacci is the "Rabbit Reproduction Problem" (also known as "Fibonacci Problem"), which was proposed by the famous Italian mathematician Fibonacci in 1202.


The No. 0 item of a series is 0, the 1th item is 1, and each subsequent item is the first two, and this sequence is the famous Fibonacci sequence, and the nth term of the Fibonacci sequence is obtained.


f[0]:=0; F[1]:=1;

For i:=2 to n do f[i]:=f[i–1]+f[i–2];


It can be seen from this question that in calculating each item of the Fibonacci series , the first two can be introduced. In this way, the changes between the two adjacent items have certain regularity, we can generalize this law into the following simple recursive relation : Fn=g (Fn-1), this is in the sequence of numbers, the relationship between the latter and the preceding paragraph is established. Then, starting with the initial condition (or the final result), recursive the relationship until the final result (or initial value) is calculated. Many of these problems are solved gradually.

For a test question, if we can find the last relationship with the previous item and know its starting condition (or the end result), the problem can be pushed forward, and then the computer will be put to the next step. Let high-speed computers do this repetitive operation, really play the "best-effort" effect.

The recursive concept given a number of sequences h0,h1,..., Hn,... If there is an integer n0, so that when n>n0, you can use an equal sign (or greater than, less than) the HN with some of the preceding items hi (0<i<n), such a formula is called a recursive relationship.
    • How to set up a recursive relationship

    • What is the nature of a recursive relationship?

    • How to solve a recurrence relationship

General steps to solve a recurrence problem
    • Set up a recursive relationship

    • Determining boundary conditions

    • Recursive solver

Two forms of recursion

Shun-push method and backward-pushing method

Recursive application classification
    • General recursion problem

    • Combinatorial counting class Problems

    • Solving a kind of game problem

    • Recursive relationship of dynamic programming problems

(i) Application of recursion (general recursion problem)

Example 2: Output the first n rows of the Yang Hui Triangle (HDOJ2032)

Problem description Remember the Yang Hui triangle you learned in high school? Specific definitions are no longer described here, you can refer to the following graphs:
1 1
1 2 1
1 3 3 1
1 4 6) 4 1
1 5 5 1Input The input data contains multiple test instances, and each test instance input contains only one positive integer n (1<=n<=30), representing the number of layers of the Yang Hui triangle that will be output. Output corresponds to each input, export the Yang Hui triangle of the corresponding number of layers, separated by a space between the integers of each layer, and a blank line behind each Yang Hui triangle. Sample Input2 3Sample Output11 1 11 11 2 1 The code is as follows:
#include <iostream>using namespacestd;inta[ to][ to];intMain () {intI,j,n; a[0][0]=a[1][0]=a[1][1]=1;  for(i=2; i< to; i++) {         for(j=0; j<=i; J + +) {            if(j==0|| i==j) {A[i][j]=1; } Else{A[i][j]=a[i-1][j-1]+a[i-1][j]; }        }    }     while(cin>>N) { for(i=0; i<n; i++) {             for(j=0; j<=i; J + +) {                if(j!=0) cout<<" "; cout<<A[i][j]; } cout<<Endl; } cout<<Endl; }     return 0;}
Example 3:hanoi tower problem.

The Hanoi Tower consists of n different sizes of discs and three pillars a,b,c. At the beginning, the N discs are set from large to small in turn on the A-bar, shown in 1. It is required to move the N disks on column A to the C column as follows:

(1) Only one disc can be moved at a time;

(2) The disc can only be stored on three bars;

(3) in the process of movement, the market is not allowed to press the small plate.

Q. How many disks do you need to move the n plates from column A to column C?


When N=1: a->c

When n=2: a->b,a->c,b->c

When n=3:

Set f (n) to the minimum number of disks required to move n plates from 1 to 3 bars.

When N=1, f (1) = 1.

When n=2, f (2) = 3.

And so on, when there are N (n>2) plates on the 1 bar, we can take advantage of the following steps:

The first step: Move the n-1 plate above the 1 bar to the 2 bar with the help of 3 bars, and the required number of moves is f (n-1).

Step two: Then move the bottom of the 1-pillar plate to the 3-column, which requires only 1 plates.

Step three: Move the n-1 plate on the 2 bar to 3 with the help of 1 bars, and the required number of moves is f (n-1).

From the above 3 steps, the total number of moving plates is: f (n-1) +1+ F (n-1).

So: f (n) =2f (n-1) +1

Hn=2hn-1+1 =2n-1 boundary Condition: h1=1

(ii) recursive application (total number of groups)

Example 4: Counting the numbers

"Problem description" we asked to find the number of the following properties (containing the natural number of the input n), first enter a natural number n (n≤1000), and then the natural number is treated as follows:
1. Do not make any treatment;
2. Add a natural number to the left of it, but the natural number cannot exceed half of the original number;
3. After adding a number, continue to proceed according to this rule until no more natural numbers can be reached;

Method 1: Use recursion

Use h[n] to indicate the number of data that the natural number n can extend, then: h[1]=1,h[2]=2,h[3]=2,h[4]=4,h[5]=4,h[6]=6,h[7]=6,h[8]=10,h[9]=10. Analyze the data, you can get the recursive formula:H[I]=1+H[1]+H[2]+...+H[I/2]. Time complexity O (n2).

Method 2: Is an improvement to Method 1. We define the array s

S (x) =h (1) +h (2) +...+h (x),

H (x) =s (x)-S (x-1)

The time complexity of this algorithm can be reduced to O (n).

Method 3: or use recursion

As long as careful analysis, in fact, we can also get the following recursive formula:

(1) When I is odd, H (i) =h (i-1);

(2) When I is even, H (i) =h (i-1) +h (I/2);

"Example 6" pass game

"Problem description" on physical education, little teacher often take the students to play together. This time, the teacher took the students together to do the passing game.
The rules of the game are like this: N (3<=n<=30) a classmate stood in a circle, one of the students holding a ball, when the teacher began to pass the whistle, each classmate can pass the ball to their own about two students of one (left and right), when the teacher again blowing whistle, pass stop, at this time, Holding the ball did not come out of the classmate is the loser, to show you a show.
The clever little man raises an interesting question: how many different passing methods can make the ball from the beginning of the small hand, pass the M (3<=m<=30) times, and back to the small hands. Two passes are seen as different methods, and only if, in both methods, the students who receive the ball are in a sequence that is different from each other. For example, 3 students 1th, 2nd, 3rd, and assume that the small is 1th, the ball passed 3 times back to the small hands of the way there are 1->2->3->1 and 1->3->2->1, a total of two.


Set F[i][k] said after the K-pass to the number of people in the hands of the number of programs, the ball to I can only come from the left of I classmate and a classmate on the right, the number of the two students are i-1 and i+1, so you can get the following recursive formula:


F[1][k]=f[n][k-1]+f[2][k-1], when I=1

F[n][k]=f[n-1][k-1]+f[1][k-1], when I=1

Boundary condition: f[1][0]=1; results in f[1][m].

Core code:

Cin>>n>>M;memset (F,0,sizeof(f)); f[1][0]=1; for(k=1; k<=m;k++) {f[1][k]=f[2][k-1]+f[n][k-1];  for(i=2; i<=n-1; i++) f[i][k]=f[i-1][k-1]+f[i+1][k-1]; F[N][K]=f[n-1][k-1]+f[1][k-1];} cout<<f[1][m]<<endl;

(c) Recursive application (total number of groups)

Number of Catalan

Definition: cn=n+2 polygon, the number of schemes that can be divided into triangles, such as a 5-sided split scheme:

, there is a positive n+2 edge shape. Take one side, starting at the end of this side, clockwise to the vertex number: 0,1,2,3,...., n,n+1 (The edge end number taken is: 0,n+1). In this way, there are n vertices in addition to the vertex of the line segment: three-way,..., N. We take the segment as one edge of the triangle, and the other vertex is I (1<=i<=n).

We set the test instructions requirements for the number of triangulation scheme H (n), that is, except for the line vertices (numbered 0 and n+1), there are n vertices when the triangulation scheme is H (n). The vertex 0,i is the subdivision number H (i-1) of the specified segment (which also has a,..., i-1, a total of i-1 vertices), and the cut fraction of the specified segment with vertex n+1,i is H (n-i). According to the multiplication principle, the 0,i,n+1 is a split triangle of the split score should be: H (i-1) *h (n-i), i=1,2,..., N, the resulting split is different, according to the addition principle is: This is consistent with the expression of Catalan C (n). So the answer is H (n) =c (n).

When the concrete implementation, if directly using the above formula calculation, the accuracy of the number of high demand. You can turn it into a recursive type:

The recursive calculation is performed again, and note that the definition of the type is to be long-length integer.

(iv) Application of recursion (game problem)

Example: Take a straight line chess problem.

A square numbered 1 to N, as shown below:

Now by the computer and human machine to the game, from 1 to N, each time you can walk K squares, where k is set S={A1,A2, A3,.... am} elements (m<=4), who first went to the nth lattice to win, try to design a man-machine to the game plan, The whole process of the game to touch the situation and strive to the computer as far as possible.


Conditions: If who first go to the nth lattice who will win, for example, assuming s={1,2}, from the nth block forward backward, then go to the first N-1 or the N-2 of the party will be defeated, and go to the first N-3 the person must win, so after the n,s determined, each square in the game, The negative or the state (both sides cannot reach the nth lattice) can be determined beforehand. The target is set to win state, from backward to backward push each of the winning and losing states, the rules in their own current lattice, if the other side no matter where they must fail, then the current lattice is the winning state, if you go after any of the lattice for the winning lattice, then the current lattice is the state, otherwise, and state.

Set 1 for the winning state, 1 for the must-fail state, 0 for the state or for the unreachable chess grid.

For example, if you set n=10,s={1,2}, you can determine the status of each of its chess cells as follows:

When n=10,s={2,3}, the state of each of its cells will be as follows:

With the state diagram of the chess lattice, the program should be able to determine who to go first, the computer to choose the winning strategy or the two sides and (both sides can not reach the target grid) strategy to play chess, you can ensure that the computer as possible unbeaten.

(v) Recursive application (recursive in dynamic programming)

Example: Check the number of squares

In a nxm square, M is an odd number, placed there are NXM,, the middle of the box below a person, the person can follow five directions but not the more squares, see right. A person must take the number of squares in a square every walk. Required to find a path from the bottom to the top, so that its number is combined with the maximum. The maximum value of the output and.


We use coordinates (x, y) to uniquely determine a point where (M,n) represents the upper-right corner of the graph, while the starting point of the person is the limit of the direction of the person to go, the point that can be reached directly (x, y) only (x+2,y-1), (x+1,y-1), (x,y-1), (x-1,y-1), (X-2, Y-1). The path to the point (X, y) and the largest path must be generated from (m/2,0) to (X+2,y-1), (x+1,y-1), (x,y-1), (x-1,y-1), (x-2,y-1) several paths, since the optimal scheme is required, of course to pick one and the largest path, The relationship is as follows:

Fx,y= max{fx+2,y-1, Fx+1,y-1,fx,y-1,fx-1,y-1,fx-2,y-1}+numx,y,

Where Numx,y represents the number on the (x, y) point.

Boundary conditions are:

The relationship between dynamic programming and recursion

The above question is actually solved by using dynamic programming, so what is the relationship between the recursive drive state planning?

We may as well draw a picture (e.g.). However, it is generally understood that the recursive relationship is a general recursive relationship, so the dynamic programming and recurrence relationship is two independent individuals.

1, generally recursive boundary conditions are obvious, dynamic planning boundary conditions are relatively hidden, easy to be neglected

2, the general recursion mathematics is strong, the dynamic programming mathematics is relatively weak

3, general recursion generally does not divide the stage, the dynamic programming generally has the more obvious stage

PS: More recursive exercises, you can see the topic of recursive solution exercise

Algorithm--Recursive strategy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.