Case of recursive algorithm

Contents Introduction

  • 01. What is the recursive
  • 02. recursive three conditions
  • 03. Fibonacci number
  • 04. find all the files in the specified directory
  • 05. seeking 1 + 2 + ... + N and
  • 06. factorial 100
  • 07. ordered array merge
  • 08. Seeking a number of power
  • 09. knapsack problem
  • 10. Select a team
  • 11. Tower of Hanoi problem
  • 12. Find a dichotomy
  • 13. alert double counting
  • 14. The open-source projects recommended

01. What is the recursive

  • Recursive: to call itself within a method. Recursion can use a simple program to solve complex problems. For example: Calculate Pei Fibonacci number sequence, Tower of Hanoi, fast discharge and other issues.
  • Recursive structure comprises two parts:
    • 1, the first recursive definitions. Answer: When not call itself method. If there is no head, into an infinite loop, that is, the end condition recursive.
    • 2, recursive thereof. ANSWER: When do I need to call their own methods.

02. recursive three conditions

  • Recursive three conditions need to be met. This is just a very typical example of recursion, then what kind of problems you can use recursion to solve it? I summed up the three conditions, as long as meet the following three conditions, you can use recursion to solve.
  • 1. Solutions of a problem can be decomposed into several sub-solution of the problem
    • What is the problem child? Sub-problem is the data size of smaller problems. For example, an example of speaking in front of a movie theater, you know, "their row in which" the problem can be decomposed into "man in the front row of the row which" such a problem child.
  • 2. The problem with sub-problems after decomposition, in addition to the different size of the data, solving thinking exactly the same
    • For example, a movie theater that example, you solved "their row in which" the idea, and in front of a line of people to solve "their row in which" the idea is exactly the same.
  • 3. The existence of a recursive termination condition + the problem into sub-problems, handle questions and then broken down into sub-sub-problems, layer by layer decomposition continues, there is not an infinite loop, which requires termination condition.
  • Or an example of the cinema, the first row of people do not need to continue to ask anyone, they know what the row, that is, f (1) = 1, which is the termination condition is recursive.

03. Fibonacci number

  • Questions asked
    • We all know that Fibonacci number, and now asked to enter an integer n, you export item n Fibonacci Fibonacci number sequence. n <= 39
  • What is the Fibonacci number?
    • 1,1,2,3,5,8,13,21 ...... Fibonacci number from the beginning of the third term, each of which is equal to the sum of the first two. Fibonacci number was proposed by the mathematician Leonardoda Fibonacci breeding of rabbits as an example, it is also called "Rabbit series."
  • Problem-solving ideas
    • To be sure, this question is in the affirmative by a recursive way to do it, but this will be a big problem, and that is a lot of double counting recursion can cause memory overflow. Further iterative method may be used, with the results stored fn1 and fn2 calculation process and reuse them. The following sample code I will give out two methods are given running time of two methods of comparison.
  • Iterative method:
  • Recursive: f (n) = f (n-1) + f (n-2)
  • Execution Time Comparison
    • We assumed that n is 40 are calculated using an iterative method and the recursion method, is calculated as follows:
      • 1. Iterative Method: 1ms time-consuming
      • 2. recursion: 272ms time-consuming
  • Why the low efficiency of recursive
    • If a simple analysis of execution flow of the program, you will find what the problem is, in order to compute Fibonacci (5), for example
    • As can be seen from the figure, the calculation Fib (5) of the process, Fib (1) is calculated twice, Fib (2) is calculated three times, Fib (3) counted twice, had only 5 calculations We can complete the task was calculated nine times. The problem with the increase in the scale will become more prominent, so that in the (1000) can no longer acceptable time to calculate Fib.
    • It was used to define a simple request fib (n), i.e. using the formula fib (n) = fib (n-1) + fib (n-2). This idea is very easy to think of, but a closer look, we found that when calling fib (n-1), but also calls fib (n-2), that is to say fib (n-2) is called twice , the same token, the call f (n-2) f (n-3) is also called twice, while the redundant call is completely unnecessary. Can calculate the complexity of the algorithm is exponential.
  • Comparison of Iterative efficiency
    • Recursive call is actually a function call themselves in their own, and function call overhead is great, the system to be called to allocate storage space for each function, and will be recorded call point push. And at the end of the function call, but also to free up space, popped restore breakpoints. So, the function call is not only a waste of space, but also a waste of time. It's a lot of time wasted on processing of the function call.

04. find all the files in the specified directory

  • Question is as follows:
    • All files in the list (or delete) the specified directory
  • Examples of the code as follows
  • Test code

05. seeking 1 + 2 + ... + N and

  • Questions asked
    • Question is as follows:
      • Calculated from the 1 + 2 + 3 + ... + N and
    • Example:
  • Examples of the code as follows
  • Test code

06. factorial 100

  • Question is as follows:
    • Factorial 100
  • Examples of the code as follows
  • Test code

07. ordered array merge

  • Question is as follows:
    • Give you two ordered arrays, a is {1, 3, 4}, b is {2, 3, 5, 6}, he requested a new synthetic array, then the output ......
  • Examples of the code as follows
  • Test Results

08. Seeking a number of power

  • Question is as follows:
    • Seeking a number of power
  • Example:
  • problem analysis
    • Seeking a bit more complicated in general can multiplication calculator point above a number, usually above the calculator key flag is x ^ y, y denotes x to the power demand. Under normal circumstances we are seeking how to multiply a number of it?
    • Mathematical formula is established as follows: (Xa) b = Xa * b
    • If the power required if the 28, we first assume that A = 22, then 28 = (22) 4, it is A4; assuming a2 = b, then A4 = b2, and b2 can be written as (b2) 1. Now then is converted into 28: b * b
    • That is the power of our operation is converted into multiplication. Xy demand value, when y is an even number, the last two can be converted into the number of multiplication, then when y is odd, the last return value must be multiplied by additional behind a x.
    • Y ^ = X (X 2) (Y / 2), the definition of a = x ^ 2, b = y / 2, is obtained of the form: x ^ y = a ^ b ;
  • Examples of the code as follows
  • Test Results

09. knapsack problem

  • Question is as follows:
    • Knapsack problem is a classic problem in the computer. In the simplest form, including attempts to data items into different weight of the backpack, the backpack so that the total weight of the final reaches specified.
  • Example:
    • For example: Suppose you want to make accurate load backpack 20 pounds can be placed, and there are five data items, respectively, their weight is 11 pounds 8 lbs, 7 lbs, 6 lbs, 5 lbs. This problem may be very simple for humans, we probably can calculate 8 lbs + 5 + 7 lbs pound = 20 lbs. But if you let the computer to solve this problem, we need to set up detailed instructions to the computer.
  • problem analysis
    • First, if at any point of this process, the sum of the data items selected in line with the target weight, then the work is complete.
    • Second, from the first data item selection started, target weight plus the remaining data items and must comply with the backpack weight by subtracting the first data item, which is a new target weight.
    • Third, the possibility of test items for each of the remaining data combined individually, but be careful not to try all combinations, and greater than the target weight because of time as long as the data item, they stop adding data.
    • Fourth, if there is no suitable combination, to give a first data item, and repeat the whole process starts from the second data item.
    • Fifth, continue to start from the third item, and so on until you have tested all combinations, then know that there is no solution.
  • Examples of the code as follows
  • Test Results

10. Select a team

  • Question is as follows:
    • In mathematics, the combination is a selection of things, regardless of their order.
  • Example:
    • For example there are five climbers, entitled A, B, C, D and E. Want these five players to select three players in Dengfeng, how this time to list all the players combined. (Without regard to order)
  • problem analysis
    • Or to the idea of ​​recursion to solve: First, the combination of these five individuals selected three people divided into two parts, the first part contains the A team, the second part does not contain the A team. Suppose the three individuals selected from a combination of 5 individual abbreviated as (5,3), n is a predetermined size of these people, and k is the size of the team. Then according to the law can have:
    • (n,k) = (n-1,k-1) + (n-1,k)
    • 3 for selecting individuals from 5 individuals,
    • Are: (5,3) = (4,2) + (4,3)
    • (4,2) indicates a player has A, and selects two players from the remaining four players, the (4,3) is removed A player from 5 individuals, the remaining four members selected 3 two members, both of the addition is selected from three members of the five members.
    • Now converting a big problem for the two small problem. Twice a choice (a choice two, once selected 3), instead of selecting three from five individuals from the crowd of four people in the crowd.
    • Select two individuals from the four people in the crowd, but also can be expressed as: (4,2) = (3,1) + (3,2), and so on, it is easy to think of the idea of ​​recursion.
  • Examples of the code as follows
  • Test Results

11. Tower of Hanoi problem

  • Question is as follows:
    • Tower of Hanoi is an ancient puzzle made up of many placed on the composition of the three pillar base plate. All plates are different in diameter, and has a central hole in the plate so that they can be placed just on the pylon. All dishes are placed in the beginning of the A-pillar base. The puzzle's goal is that all the dishes are from pylon to pylon A mobile C, a time to move a plate, and the plate is not any smaller than can be placed on their plates.
  • Example:
    • Imagine if only two plates, dishes named after our small to large numbers (also imagine diameter), two plates above the plate is 1, the following is the plate 2, then we only need to move to the first plate 1 Tower B holder, and the plate 2 is moved to the pylon C, and finally the plate 1 is moved to the C-pillar base. Complete two plates move from A to C.
    • If there are three plates, the plates will be 1 into C pylon, the pylon plate 2 into the B, C in the plate 1 onto the pylon pylon B, A pylon and then into the plate 3 C pylon, and the pylon plate 1 B into a pylon, the pylon plate B into C pylon 2, a pylon and finally placed on the plate C 1 pylon.
  • problem analysis
    • If there are four, five, N a plate, then how should we do it? This time recursive mind is a good solution to this problem, when only two plates, we only need to pylon B as an intermediary, the intermediary plate 1 first placed on the B pillar base, then put the tray 2 target Tazuo C, and finally on the intermediary plate onto the target pylon pylon B C can be.
    • So no matter how many dishes, we will think of it as only two plates. Suppose there are N to the pylon plate A, we will see it as two plates, wherein the (N-1) ~ 1 a plate as a plate, the bottom plate of the N as a plate, then the solution Measures are:
      • ①, A pylon of first (N-1) ~ 1 a plate as a plate, placed on the interposer pylon B, and the N-th target plates on the pylon C.
      • ②, A pylon is empty then, as is the intermediary pylon, which pylon has a B time of N-1 plate, the first (N-2) ~ 1 a plate as a plate, onto the intermediary Tazuo the a, B and the pylon No. (N-1) on the target plates on the pylon C.
      • ③, A pylon this time there is a (N-2) a plate, B Tazuo considered empty interposer pylon, the pylon B turn, repeated ①, ② step, until all the plates are placed in the target pylon C on end.
    • In simple terms, with steps like the elephant in the refrigerator, a recursive algorithm:
      • ①, A pylon moves from the initial n-1 comprises a plate to the intermediary pylon B.
      • ②, the remaining a plate (a plate maximum) Initial pylon onto the target A pylon C.
      • ③, the n-1 will move onto a target plate on the interposer pylon pylon C B.
  • Examples of the code as follows
  • Test Results

12. Find a dichotomy

  • Question is as follows:
    • A series array, and then find an index value
  • problem analysis
    • You must be sorted list Sort Down can
  • Examples of the code as follows
  • Test Results

13. alert double counting

  • In addition, there will be double counting when using recursion. A third example of recursive code just said, if we look at the whole recursive decomposition process, then it is this:
  • Want to calculate f (5), you need to calculate f (4) and f (3), calculated f (4) also need to calculate f (3), and therefore, f (3) was calculated many times, and this is double-counting problem.
  • To avoid double counting, we can save had already solved f (k) by a data structure (such as a hash table). When the recursive call when f (k) to next look at whether already solved before. If so, the return value directly from the hash table, without double counting, so you can just avoid talking about the problem.
  • According to the above ideas, we just look to transform the code:
  • In addition to a stack overflow, double counting of these two common problems. Recursive code that there are many other problems. Efficiency in terms of time, a lot more code recursive function call, when a large number of these function calls, it will accumulate into a significant time cost.

14. The open-source projects recommended

Guess you like

Origin www.cnblogs.com/yc211/p/12071513.html