Classic Example of Backtracking Method - Python

1. Seven segment code: practice system
Solution: The idea is to combine, first use a hash table to store all characters and their adjacent characters, and then find the combination that meets the requirements. The code explanation is as follows (you can improve it yourself), and for another direct brute force algorithm, please refer to this article.

#seven segment code #combination + backtracking 
Last={'a':['b','f'],'b':['a','c','g'],'c':['b','g','d'],'d':['c','e'],
'e':['d','f','g'],'f':['a','e','g'],'g':['b','c','e','f']}#hash storage 
def bfs(path,s,n):#define a backtracking function 
if len(path)==n:#end condition 
  kk=''.join(sorted(path))#sort combinations by size 
  if kk not in AA:#whether the condition requirements are met 
      AA.append(kk)#result increase 
  return
for i in Last[s]:
  if i not in path:#pruning operation 
      path.append(i)#add path 
      bfs(path,i,n)#next node 
      path.pop()#path backtracking 
if __name__=='__main__':
AA=[]
for n in range(1,8):
  for j in 'abcdefg':
      bfs([j],j,n)#calling backtracking functions 
print(len(AA))
print(AA)

Output results and combinations that meet the requirements:
2. Annual string size: Practice system

#year string font size #backtracking + combination 
import itertools
SS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def dfs(path,n):
if len(path)==n:#end condition 
  VAL.append(''.join(path))#result increase 
  return
for i in SS:#simple combination, so there is no need to add judgment conditions during pruning operations 
  path.append(i)#increased road strength 
  dfs(path,n)#next node 
  path.pop()#backtracking 
if __name__=='__main__':
VAL=[]
for i in range(1,4):
  dfs([],i)
print(VAL.index('AZ'))
print(VAL.index('AB'))
print(VAL.index('LQ'))
print(VAL[2018])

Another solution is as follows: it takes 26 cycles, and look at the last digit (i.e. the last letter) of the 2019 cycle. It means splitting 2019, but its cycle is a multiple of 26.

#year string font size #find patterns 
# #individual bit 
# a = 2019 % 26
# b = 2019 // 26
# #ten digit 
# c = b % 26
# #hundred places 
# d = b // 26
# list = '*ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# print(list[d] + list[c] + list[a])

3. Decomposition of positive integers: It is also a combinatorial idea, but as the number increases, the time complexity is higher.

#decomposition of integers #backtracking method 
def Fenjie(path,SS,n):
if sum(SS)==num:
  # print(SS)
  GG.add(tuple(SS))
  return
if n>=len(Com_Val):
  return
for i in range(n,len(Com_Val)):
  if i not in path:#pruning 
      path.append(i )path addition 
      SS.append(Com_Val[i])#next node 
      Fenjie(path,SS,i+1)
      path.pop()
      SS.pop()
if __name__=='__main__':
num=int(input())
Com_Val=[]
for i in range(1,num):
  Com_Val+=[i]*(num//i)#indicating that at most N//i individual i form 
print(Com_Val)
GG=set()
for i in range(len(Com_Val)):
  Fenjie([i],[Com_Val[i]],i+1)
print(GG)

Here is a recommendation for a young man's idea: to find its state and each transition state.

#decomposition of positive integers 
def dfs(n,m):
if n<=0 or m<=0:#there is no situation of decomposing into 0 or negative values 
  return 0
if n==1 or m==1:#there is only one scenario when decomposing to a minimum value of 1 
  return 1
if n==m:#when decomposing oneself with oneself, it is equivalent to decomposing one's own situation with a smaller number than oneself +1
  return 1+dfs(n,m-1)
if n<m:#when decomposing oneself into a larger number than oneself, because there is no negative value, it is equivalent to decomposing oneself using oneself 
  return dfs(n,n)
if n>m:#when the decomposition of one's own number is smaller than oneself, there are two situations: one is to include the decomposition number itself dfs(n-m,m )one is to not include the decomposition number itself 
  return dfs(n-m,m)+dfs(n,m-1)
if __name__=='__main__':
N=int(input())
print(dfs(N,N))

4. Check another article on circuit counting
5. Queen N's Question:

#N queens problem 
def judge(i,j,Zuo):
for nn in range(1,N+1):
  if (i+nn,j-nn) in Zuo or (i+nn,j+nn) in Zuo or (i-nn,j-nn) in Zuo or (i-nn,j+nn) in Zuo:
      return False
else:
  return True
def DFS(X,Y,path):#backtracking function 
if len(path)==N:
  num=sorted(path,key=lambda x:x[0])
  if tuple(num) not in KK:#the purpose of adding this selection condition is to remove duplicates 
      print(num)
      KK.add(tuple(num))
  return
for i in range(N):
  if len(path)!=0 and path[0][0]==1:#the purpose of adding this condition is also to remove duplicates 
      break
  for j in range(N):
      if i not in X and j not in Y and judge(i, j, path):#pruning operation 
          X.append(i)#path addition 
          Y.append(j)
          path.append((i, j))
          DFS(X,Y,path)#next node 
          X.pop()#backtracking 
          Y.pop()
          path.pop()
if __name__=='__main__':
KK=set()
N=int(input())
DFS([],[],[])#the time complexity is n**n
print(len(KK))
print(KK)