In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the backtracking algorithm". Interested friends might as well take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what the backtracking algorithm is.
What is the backtracking algorithm
The backtracking algorithm is actually a search attempt process similar to enumeration, which mainly looks for the solution of the problem in the process of search attempt. When it is found that the solution condition has not been met, the backtracking algorithm returns and tries another path. Many complex and large-scale problems can use retrospective method, which has the laudatory name of "general problem-solving method".
The backtracking algorithm is actually a depth-first search attempt process similar to enumeration, which mainly looks for the solution of the problem in the process of search attempt. When it is found that the solution condition has not been met, the backtracking algorithm returns (that is, recursive return). Try another path.
Question of the eight queens:
The N Queen problem requires solving all possible board layouts in which N queens are placed on Numbn's chessboard and the queens are protected from each other. The condition that queens are not attacked by each other is that no two queens can appear in the same row, column or diagonal on the chessboard.
Since the N queen problem does not allow two queens to be in the same row, an one-dimensional array X can be used to denote the solution of the N queen problem, and X [I] represents the column number of the queen in line I. The key is to find out the unavailable points in the line to be processed in the code.
Solving the N Queen problem by the above X array ensures that any two queens are not on the same line, and other conditions for judging that the queens are not attacked by each other can be described as follows:
X [I] = X [s], then row I is in the same column as the queen in row s.
If the queens in row I are in column j and the queens in row s are in column t, that is, X [I] = j and X [s] = t, then as long as iMui j = smurt or iMeij = squit, it means that the two queens are on the same diagonal.
After transforming the two equations, it is concluded that the queen is on the same diagonal as long as | imurs | = | jmurt | (that is, imurs = X [I]-X [s]).
To solve the N queen problem, we need to traverse the space tree to determine whether the chessboard layout of the current node meets the requirements at any time, and then continue to traverse downward until we get a leaf node that meets the constraints, so as to get a chessboard layout that meets the requirements; the nodes that do not meet the requirements will be discarded (called pruning) and traced back to the nodes in the upper layer to continue traversing. When the traversal of the whole tree is finished, all the chessboard layouts that meet the requirements have been obtained.
Public class Queen {/ / the number of options public static int num = 0; / / the number of queens public static final int MAXQUEEN = 8; / / defines an array indicating the position of the queens in the MAXQUEEN chess pieces public static int [] cols = new int [MAXQUEEN]; public void getCount (int n) {boolean [] rows = new boolean [MAXQUEEN] For (int m = 0; m
< n; m++) { // rows 为true 表名不可以放,垂直上面不可放 rows[cols[m]] = true; int d = n - m; // y=x 这条线 往前判断 if (cols[m] - d >= 0) {rows [cols [m]-d] = true;} / / the line to the right of if (cols [m] + d knapsack problem:
Problem: given n items and a backpack. The weight of item I is wi, its value is pi, and the capacity of backpack is C. How to choose the items in the backpack to maximize the total value of the items in the backpack?
Analysis: the problem is that some of the items are selected from n items, and the solution space of the problem is a subset tree. For example, when the number of items is 3, the solution space tree is shown in the following figure. An edge of 1 represents the selection of the item, and an edge of 0 indicates that the item is not selected. Use x [I] to indicate whether the item I is put in the backpack, x [I] = 0 to not, and x [I] = 1 to put it in. Backtracking the search process, if you come to the leaf node, it indicates the end of a search path, and if there is a better solution on that path, it will be saved. If it is not a leaf node, but a midpoint node (such as B), traverse its child nodes (D and E), and if the child node meets the pruning condition, continue to search backwards for the child node.
[overall thinking]
01 knapsack belongs to the problem of finding the optimal solution, and the subset tree of the solution needs to be constructed by backtracking method. For each item I, there are only two decisions on whether to choose or not to choose the item, there are a total of n items, and each item can be considered sequentially, thus forming a solution space tree: the basic idea is to traverse the tree to enumerate all the situations. finally, it is judged that if the weight does not exceed the capacity of the backpack and the value is the most, the scheme is the final answer. The meaning of deep traversal.
Package practice; / * given n items and a backpack. The weight of item I is wi, its value is pi, and the capacity of backpack is C. Ask how to select the items in the backpack to maximize the total value of the items in the backpack? * * @ author fulisha * * / public class _ 05 {static int BestValue = 0; / / the current maximum value is initialized to 0 static int [] BestX; / / optimal solution BestX [I] = 1 means item I is put in the backpack, 0 means not put / / static int CurWeight = 0; / / the total weight of the item currently put in the backpack static int CurValue = 0; / / the total value of the item currently put in the backpack static int N = 3ramp / item quantity static int C = 16 / / Total capacity of items static int W [] = {10,8,5}; / / weight of each item static int v [] = {5,4,1}; / / value of each item static int x [] = {0,0,0} / / x [I] = 1 means the item I is put into the backpack, 0 means not put into public static int backtrack (int t) {/ / if it is the current value and the best value of the child node to judge and save the best value if (t > N-1) {if (CurValue > BestValue) {BestValue = CurValue } return BestValue;} / / if it is not a child node to traverse the child node else {/ / take or not use 0max 1 to denote for (int I = 0) I =) number of if (timer
< 0 || timer >N / 2) {return } else {if (k [I] = ='(') {timer++ } else {timer-- If (timer = = 0) list.add (temp);}} = import java.util.ArrayList;import java.util.List Public class generateParenthesis {/ / parameters have n pairs of {} () [], public static List generater (int n) {List result=new ArrayList (); generaterOneByOne (", result,n,n); return result } / * left: the parentheses on the left are n * right: the parentheses on the right have n * thoughts: * you must first put the parentheses on the left in a recursive way, and then until the number of parentheses on the left is less than 0, and when the parentheses on the right is 0 Cut off and put it in the result * the parenthesis on the right should be put back: that is, right > left Make sure that the number of closing parentheses is greater than the number of left parentheses * @ param substring * @ param result * @ param right * / private static void generaterOneByOne (String substring, List result, int left, int right) {if (left==0&&right==0) {result.add (substring) Return;} if (left > 0) {generaterOneByOne (substring+ "(", result, left-1, right);} if (right > left) {generaterOneByOne (substring+')', result, left, right-1) At this point, I believe you have a deeper understanding of "what is the backtracking algorithm". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 235
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.