Backtracking algorithm:
From a road to go forward, can enter into, not into the back, change a way to try again. (Search in Depth-first mode)
The backtracking method is an optimal search method, which is searched forward according to the selection criteria to achieve the goal. But when you explore a step and find that the original choice is not optimal or not reach the goal, return to a step to re-choose.
When you use backtracking to find any solution, you can end it by searching for a solution to the problem.
When you use backtracking to find all the solutions to a problem, you go back to the root, and all the viable subtrees of the root node are searched and finished.
There are two ways to implement backtracking: recursion and recursion (also called iteration). In general, both methods of a problem can be implemented, but there are differences in algorithmic efficiency and complexity of the design.
Recursive thinking is simple, easy to design, but inefficient. Recursive algorithm design is relatively complex, but high efficiency.
Sets the power set function:
public class test{
public static void Main (String []args) {
list<string> list = new arraylist<string> ();
List.add ("A");
List.add ("B");
List.add ("C");
list<string> li = new arraylist<string> ();
Print (0,list,li);
}
public static void print (int i, list<string> List, list<string> Li) {
if (i > List.size ()-1) {
System.out.println (LI);
}else{
Li.add (List.get (i));//Zuozi treatment
Print (i+1,list,li);//recursive traversal
Li.remove (List.get (i));//processing of right sub-tree
Print (i+1,list,li);//recursive traversal
}
}
}
Queen's question:
public class test{
static int max = 8;//Place several queens
static int num = 0;//A total of several storage methods
Static int[] Array = new int[max];//use an array to store the Queen's position to determine if it is properly placed
public static void Main (string[] args) {
Check (0);//Put the first Queen first
SYSTEM.OUT.PRINTLN (num);
}
public static void Check (int n) {
if (n = = max) {//If the Queen is all placed, total +1 and jump out of the method
num++;
Return
}
for (int i = 0; i < max; i++) {//starting from the first column to
Array[n] = i; By default the Queen is placed from the first column of the row
if (OK (n)) {//Determine if the Queen is positioned correctly
Check (n + 1); If correct, the next queen's placement
}
}
}
Private Boolean ok (int n) {
for (int i = 0; i < n; i++) {//starting from the first column and then judging if there is a conflict with the line of this column, if OK, enter the logic
Array[i] = = Array[n] To determine whether to be on the same slash
Math.Abs (n-i) = = Math.Abs (Array[n]-array[i]) determine if the same row or column
if (array[i] = = Array[n] | | Math.Abs (n-i) = = Math.Abs (Array[n]-array[i])) {
return false;
}
}
return true;
}
}
The implementation of backtracking algorithm