PackageBasealgo;ImportJava.util.Scanner;/** Recursive algorithm: repeatedly call itself to solve the problem. Requires that the problem be decomposed into a sub-problem of the same problem. * Direct recursion: Call itself * indirect recursion: A call b b then call A; (not much) * recursion before the general there is an if statement as a recursive exit, otherwise infinite call itself, throwing a stack overflow. * * Example: factorial problem*/ Public classDigui { Public Static intFactintN) { if(n<=1){ return1;//Export}Else{ returnn Fact (n-1); } } Public Static voidMain (string[] args) {System.out.println ("Enter an integer that requires factorial:"); Scanner input=NewScanner (system.in); intn =Input.nextint (); System.out.println ("The result of factorial is:" +fact (n)); }}
PackageBasealgo;ImportJava.util.Scanner;/** Recursive method: According to the existing data and relations, gradually deduced and obtained results. Often used in mathematical situations, can abstract the mathematical formula * 1. Based on known results and relationships (explicit logical relationships), the intermediate results are obtained. * 2. Judge whether to meet the requirements, if not, then continue to beg, if meet the requirements, then said to find a correct answer * * Example: A pair of two-month-old rabbits every one months after the birth of a pair of rabbits, and newborn rabbits will be born two months before the baby rabbit. If born in January, * March will not litter. Q. How many rabbits are there in a year? * Rule: The total number of rabbits per month equals the number of rabbits in the first two months. */ Public classDitui { Public Static intFibonacciintN) { intT1, T2; if(n = = 1 | | n==2){ return1; }Else{T1= Fibonacci (n-1); T2= Fibonacci (n-2);//Recursive returnT1 +T2; } } Public Static voidMain (string[] args) {System.out.println ("Recursive method to find the rabbit litter problem!" "); System.out.println ("Enter the number of months:"); Scanner input=NewScanner (system.in); intn =Input.nextint (); intnum =Fibonacci (n); System.out.println ("A pair of rabbits after" + n + "months of breeding" + "total" + num + "on the rabbit! " ); }}
PackageBasealgo;ImportJava.util.Scanner;/** Exhaustive algorithm exhaustive Attack method * relies on the computer's powerful computing power to exhaust every possible situation. Select the result that meets the requirements. * Steps to perform: 1. For one possible situation, calculate the result. 2, determine whether the results meet the needs, such as not satisfied with the first step. * Example: chicken and rabbit cage problem: There are 35 head, under 94 feet, ask the rabbit chicken geometry? */ Public classExhaustiveattackmethod {Static intChichen,rabbit; Public Static intQiongju (intFootinthead) { intRe, j, I; Re=0; for(i=0;i<=head;i++) {J=head-i; if(I*4+j*2 = =foot) {Re=1; Chichen=J; Rabbit=i; } } returnre; } Public Static voidMain (string[] args) {intRe, foot,head; System.out.println ("Using the exhaustive algorithm to calculate the cage problem of chickens and rabbits:"); Scanner input=NewScanner (system.in); System.out.println ("Please enter the number of headers:"); Head=Input.nextint (); System.out.println ("Please enter the number of feet:"); Foot=Input.nextint (); Re=Qiongju (Foot,head); if(re==1) {System.out.println ("Chicken has" + Chichen + "only," + "rabbit has" + rabbit + "only. "); }Else{System.out.println ("No solution!" "); } }}
PackageBasealgo;ImportJava.util.Scanner;/** Divide-and-conquer algorithm: A complex computational problem is divided into small size, simple calculation of small problems to solve. Then synthesize each small problem and get the final answer. * Execution Process: * 1. For a problem of size n, if the problem can be easily resolved, then resolve directly, otherwise perform the following steps. * 2. The problem of decomposition is M-scale sub-problem, these sub-problems are independent of each other, and the same as the original problem form. * 3. Solve these sub-problems recursively * 4. Then, the solution of the sub-problem is merged to get the solution of the original problem. * Example: There are 30 coins, one of which is counterfeit money, know that counterfeit money is lighter than real, ask how to find counterfeit currency? * * Analysis: The coins are divided into two piles, put on the balance to say, a lighter pile containing counterfeit money, repeat the operation, * until the remaining two, you can directly use the balance to find counterfeit money. * */ Public classFenzhi {Static Final intMaxnum = 30; Static intFindfalsecoin (intCoin[],intLow,intHigh ) { intI, sum1,sum2,sum3; intRe = 0; Sum1=sum2=sum3=0; //Two coins if(Low+1 = =High ) { if(coin[low]<Coin[high]) {Re= low + 1;//Array Initial subscript is 0, need to add a returnre; }Else{re= High+1; returnre; } } //is greater than 2 and is even if((high-low + 1)%2 = = 0){ for(i=low;i<=low+ (high-low)/2;i++) {sum1= Sum1 + coin[i];//Total weight } for(i= low + (high-low)/2+1; i<=high;i++) {sum2= sum2 + coin[i];//The total weight of the other treatment } if(sum1<sum2) {Re= Findfalsecoin (coin, Low, low+ (high-low)/2); returnre; }Else if(sum1>sum2) {Re= Findfalsecoin (Coin, low+ (high-low)/2+1, high); returnre; }Else{ } } //Odd Else{ for(i=low;i<=low+ (high-low)/2-1;i++) {sum1= Sum1 +Coin[i]; } for(i=low+ (high-low)/2+1;i<=high;i++) {sum2= sum2 +Coin[i]; } sum3=coin[low+ (high-low)/2];//Middle Number if(sum1>sum2) {Re= Findfalsecoin (Coin, low+ (high-low)/2+1, high); returnre; }Else if(sum1<sum2) {Re= Findfalsecoin (coin, Low, low+ (high-low)/2-1); returnre; }Else{ } if(sum2+sum3 = = sum1+sum3) {Re= low+ (high-low)/2+1; returnre; } } returnre; } Public Static voidMain (string[] args) {int[] coin =New int[Maxnum]; inti,n,posion; System.out.println ("Divide-and-conquer algorithm to solve fake coin problem!" "); System.out.println ("Please enter the total number of coins:"); Scanner input=NewScanner (system.in); N=Input.nextint (); System.out.println ("Enter the total amount of each coin:"); for(i=0;i<n;i++) {Coin[i]=Input.nextint (); } posion= Findfalsecoin (coin, 0, n-1); System.out.println ("In the above + n +" coins, the first "+ Posion +" is a fake coin! " ); }}
PackageBasealgo;ImportJava.util.Scanner;/** Probabilistic algorithm: Using probability statistics to solve problems, can not get the actual connection of the problem, but the approximate value can be obtained. * Basic steps: * 1. Transform the problem into the corresponding geometry the area of the s,s is easy to calculate, and the result of the question often corresponds to the area of a part of the S1 in the geometry. * 2. Then randomly scatter points to the geometry. * 3. Statistics the number of points in the geometry s and S1. The results are calculated based on the relationship of S area and S1 area and the number of points in each graph. * 4. Determine if the above results are within the required accuracy, and then proceed to step two if the accuracy is not achieved. * * Numerical probability algorithm: Monte Carlo (Monte Carlo), Las Vegas (Las Vegas), Sherwood (Sherwood). * Monte Carlo Example: Calculate pi π. */ Public classGailv {Static DoubleMontepi (intN) { DoublePI; Doublex, y; inti,sum; Sum= 0; for(i=1;i<n;i++) {x=Math.random (); Y=Math.random (); if(X*x + y*y <= 1) {sum++; }} PI=4.0*sum/N; returnPI; } Public Static voidMain (string[] args) {intN; DoublePI; System.out.println ("Monte Carlo Probabilistic algorithm calculates π:"); Scanner input=NewScanner (system.in); System.out.println ("Number of input points:"); N=Input.nextint (); PI=Montepi (n); System.out.println ("Π=" +PI); }}
5 Kinds of Algorithm ideas