Heuristics

Backtracking Algorithm (aka Heuristic Algorithm)

In order to find a solution to the problem, first select a certain possible situation for testing. In the process of testing, once the assumption of the original choice is found to be wrong, it will take a step back and re-select, continue to test forward, and so on until the get a solution or prove no solution.

 

Example: Generate lottery number combination.

     Suppose there is a lottery, each bet consists of 7 numbers 1-29, and these 7 numbers cannot be the same, write a program to generate all combinations of numbers.

 

Java code description:

public class Test {

	public static int MAXN = 7; //Set the number of digits for each group of lottery tickets
	public static int NUM = 29; //Set the numbers that make up the lottery ticket
	public static int[] num = new int[NUM];
	public static int[] lottery = new int[MAXN];
	
	public static void main(String[] args) {
		
		int i,j;
		for(i=0;i<NUM;i++){ //Set the lottery numbers
			num[i] = i+1;
		}
		for(j=0;j<MAXN;j++){
			lottery[j] = 0;
		}
		combine(NUM,MAXN);
		
	}
	public static void combine(int n,int m){
		int i,j;
		for(i=n;i>=m;i--){
			lottery[m-1] = num[i-1]; //save a digit
			if(m>1){	
				combine(i-1,m-1);
			}else{ //If m=1, output a bet number
				for(j = MAXN -1;j>=0;j--){
					System.out.print(lottery[j]+"  ");
				}
				System.out.println();
			}
		}
	}
	
}

 operation result:



 After the above program is finished, all possible points will be listed. This scenario can also be achieved by exhaustiveness.

Guess you like

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