Recursion and Divide and Conquer Strategies
1. The general idea of recursion:
For a large-scale problem that cannot be directly solved, the large problem can be divided into k small problems. If the small problems cannot be solved, continue to divide until the problem is small enough to be solved easily. Then, the solutions to the small-scale problems are combined into the solutions of a larger-scale problem, and the solutions to the original problems are gradually obtained from the bottom up.
2. The idea of divide and conquer:
Divide a big problem that is difficult to solve directly into some smaller problems of the same size, so that each can be broken down and divided and conquered.
Stop talking nonsense and see examples
Example 1. Factorial function
algorithm:
int fac (int x) { if(x==1){ return x; }else{ return fac(x-1)*x; } }
2. Recursive full permutation problem: full permutation of n elements.
public class Order { /** * Recursive full sort */ public static void main(String[] args) { int[] a={1,2,3}; pai(a,0,a.length); } public static void pai(int[] a,int start ,int end){ if(start ==end){ for(int i=0;i<end;i++){ //output statement System.out.print(a[i]); } System.out.println(); } else{ for(int j=start;j<end;j++){ int b=a[start]; a[start] =a[j]; //Swap positions a[j] =b; pai(a,start+1,end); b=a[start]; a[start] =a[j]; //Return to the original state a[j] =b; } } } }
to be continued........