algorithm recursion

                            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.

 

Design a recursive algorithm to generate a full permutation of n elements {r 1 , r 2 , , rn }.
Let R={r 1 ,r 2 , ,r n } be the n elements to be permuted, R i =R-{r i }.
The full permutation of elements in set X is denoted as perm(X).
(r i )perm(X) represents the permutation obtained by adding a prefix to each permutation of the full permutation perm(X). The full permutation of R can be inductively defined as follows:
When n=1, perm(R)=(r), where r is the only element in the set R;
When n>1, perm(R) consists of (r 1 )perm(R 1 ), (r 2 )perm(R 2 ) , , (rn )perm(R n ).
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........

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326870084&siteId=291194637