LeetCode's backtracking algorithm

Algorithm Introduction:
Back tracking (exploration and backtracking) is a kind of optimal search method, also known as heuristic method, which searches forward according to the optimal conditions to achieve the goal. However, when exploring a certain step, it is found that the original choice is not good or does not reach the goal, and then one step is returned to re-select. This technique of returning and going back is a retrospective method, and a certain point of the state that meets the retrospective condition This is called the "backtrack point".

Vernacular: The backtracking method can be understood as finding a destination by selecting different forks, trying to find the destination one by one. If you go the wrong way, continue to return to find another road at the intersection until you find your destination.

According to the definition, to achieve backtracking, two points and one search are needed. Two solution spaces The
solution space is a vector like an array [a1, a2, ..., an]. Each element of this vector is a partial solution to the problem. Only when each element of this array is filled (to get all the solutions), it shows that the problem has been answered. So the difficulty of almost all backtracking problems lies in how to define the solution space.
The following template applies to all "backspace determination" problems! ! !

def backtrack(i, n, *args)
  	if condition:
		add_answer()
	else:
		change()
 		backtrack(i+1, n, *args);
		remove_change()

Next, we will further experience the space
problem of the backtracking algorithm through the specific topic. The problem of
n queens is to study how to place n queens on an n × n chessboard, and prevent queens from attacking each other.
Given an integer n, return all different n queen solutions.
Each solution contains a clear n-queen problem piece placement scheme, where 'Q' and '.' Represent the queen and the vacancy, respectively.
Here is the backtracking core code:

 def backtrack(row):
            for col in range(len(cb)):
                if judge(row, col):
                	#开始试探
                    place_queen(row, col)
                    if row == len(cb) - 1:
                        add_cb()
                    else:
                        backtrack(row + 1)
                    #回到原点
                    remove_queen(row, col)

Problem 2
Given a character string s, divide s into substrings so that each substring is a palindrome string.
Return s all possible splitting schemes.

def backtrack(start):
    for end in range(start, len(s)):
         if judge(s[start:end + 1]):
               	temp.append(s[start:end+1])
         		if end + 1 == len(s):
               		save = copy.deepcopy(temp)
               		ans.append(save)
         		else:
               		backtrack(end + 1)
         		temp.pop()                   

Topic 3 The
accumulated number is a string, and the numbers that make up it can form an accumulated sequence.

A valid accumulation sequence must contain at least 3 numbers. Except for the first two numbers, the other numbers in the string are equal to the sum of the two numbers before it.

Given a string containing only the digits '0'-'9', write an algorithm to determine whether the given input is a cumulative number.

Explanation: The numbers in the accumulation sequence will not start with 0, so there will be no cases of 1, 2, 03 or 1, 02, 3.

#初始三个数通过for循环获取,这里只摘取回溯部分
def backtrack(num1, num2, num3, tot):
         if judge(num1, num2, num3):
                    if tot + 1 == len(num):
                        self.ans = True      
                    else:
                        for tot1 in range(tot + 1, len(num)):
                            if num[tot + 1] == '0' and tot + 1 != tot1:
                                continue
                            backtrack(num2, num3, int(num[tot + 1: tot1 + 1]), tot1)
                            

Published 16 original articles · Like1 · Visits 377

Guess you like

Origin blog.csdn.net/qq_41174940/article/details/103951204