Recursive algorithm Classic example Summary (C # Implementation)

Source: Internet
Author: User

introduction of recursive algorithm

In mathematics and computer science, recursion refers to the method of using the function itself in the definition of a function.
Recursive algorithm is a direct or indirect process to invoke its own algorithm. In the computer programming, the recursive algorithm is very effective to solve a large class of problems, it often makes the description of the algorithm concise and easy to understand.
The recursive algorithm solves the problem characteristic:
(1) Recursion is the invocation of itself in a procedure or function.
(2) When using a recursive strategy, there must be a definite recursive end condition called a recursive exit.
(3) Recursive algorithm is usually very concise, but the recursive algorithm is less efficient in solving problems. Therefore, the recursive algorithm is generally not advocated for the design of the program.
(4) in the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on to store. Too many recursion times can cause stack overflow and so on. Therefore, the recursive algorithm is generally not advocated for the design of the program. In the actual programming, especially pay attention to stack overflow problem.

With recursive method, we can transform a relatively complex problem into a small problem similar to the original problem to solve, the recursive method needs a small number of programs to describe the process of solving the problem of repeated calculations, greatly reducing the code of the program. However, there are some drawbacks when it comes to convenience, that is, the efficiency of using recursive method is not high.

second, Fibonacci series and factorial

1. Fibonacci Series

Referring to recursion, one example we might think of is the Fibonacci sequence. The Fibonacci sequence is the following sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..., in short, is the sum of the number of nth (n > 2) equals the number of N-1 and (N-2). The recursive algorithm is implemented as follows:

  Public Static intFibonacci (intN) {if(N <0)return-1; if(n = =0)return 0; if(n = =1)return 1; returnFibonacci (N-1) + Fibonacci (N-2); }

2. Factorial

Also is to ask for a number of factorial, will also use recursion, this is relatively simple, directly give implementation code,

Three, Hanoi tower problem

Hanoi is a mathematical problem formed according to a legend:

Hanoi (image from Network)

There are three Poles a,b,c. A rod has N (n>1) perforated discs, the size of the disk from bottom to top in turn smaller. The following rules are required to move all discs to the C-bar:
1, can only move one disk at a time;
2, the market can not be stacked on the small plate above.
Tip: The disc can be temporarily placed in the B-bar, or the disc removed from the A will be moved back to the A-bar, but must follow the above two rules.
Q: How do I move? How many times do you want to move at least?

Here is the recursive solution implementation of Hanoi (C # code):

 Public Static voidHannoi (intNstring  from,stringBufferstringTo ) {         if(n = =1) {Console.WriteLine ("Move Disk"+ N +" from"+ from+" to"+to ); }         Else{Hannoi (n-1, from, to, buffer); Console.WriteLine ("Move Disk"+ N +" from"+ from+" to"+to ); Hannoi (n-1, Buffer, from, to); }      }

The result of its operation (you can compare it with the GIF image above):

iv. permutations and combinations

1, the output of any number of letters, the full array of numbers

An array of strings of n or n characters (numbers, nodes) that have a total permutation of a (n, n) =n! species. This problem is also a recursive problem. For example, the full array can be obtained: {123,132,213,231,312,321}.

The following code is implemented with the recursive algorithm:

 Public Static voidPermutation (string[] Nums,intMintN) {stringT; if(M < n-1) {permutation (nums, M+1, N);  for(inti = m +1; I < n; i++)            {               //The swap method can be extractedt =Nums[m]; NUMS[M]=Nums[i]; Nums[i]=T; Permutation (Nums, M+1, N); //The swap method can be extractedt =Nums[m]; NUMS[M]=Nums[i]; Nums[i]=T; }         }         Else         { for(intj =0; J < Nums. Length; J + +)            {Console.Write (Nums[j]);         } Console.WriteLine (); }      }

The calling code is as follows:

Static void Main (string[] args)      {         newstring"a" " b " " C "  };          0 , nums.length);          Console.readkey ();      }

Here we pass a string array, ABC three letters to test, output such as:

2. Save all the results in the linked list

  Sometimes we need to save the entire array of results, and then do other things, and we can save the results in a linked list. We define the following classes as nodes of the linked list, with the following code:

    Public class Node   {      publicstringgetset;}        Public Get Set ; }        Public Node (string  value)      {         this. Value = value;            This NULL ;      }   }

The global variables are declared at this point, as follows:

 Public Static New List<node> ();

This time, we modify the permutation method as follows:

   Public Static voidPermutation (string[] Nums,intMintN) {stringT; if(M < n-1) {permutation (nums, M+1, N);  for(inti = m +1; I < n; i++)            {               //The swap method can be extractedt =Nums[m]; NUMS[M]=Nums[i]; Nums[i]=T; Permutation (Nums, M+1, N); //The swap method can be extractedt =Nums[m]; NUMS[M]=Nums[i]; Nums[i]=T; }         }         Else{Node root=NULL;            Node CurrentNode;  for(intj =0; J < Nums. Length; J + +) {CurrentNode=NewNode (Nums[j]); Currentnode.nextnode=Root; Root=CurrentNode;         } nodelist.add (root); }      }

Thus, after we have executed the permutation method, we save the results to the linked list. When used, we just have to traverse the nodelist.

The recursive algorithm comes first here. When it comes to algorithms, it is necessary to mention the data structure, it seems really to "learn the old" ~ ~

Cloud drizzling

QQ Exchange Group: 243633526

Blog Address: http://www.cnblogs.com/yunfeifei/

Disclaimer: The original text of this blog only represents my work in a certain time to summarize the views or conclusions, and my unit does not have a direct interest in the relationship. Non-commercial, unauthorized, post please keep the status quo, reprint must retain this paragraph statement, and in the article page obvious location to the original connection.

If you feel that my blog is helpful to everyone, please recommend supporting one, give me the motivation to write.

Recursive algorithm Classic example Summary (C # Implementation)

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: info-contact@alibabacloud.com 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.