Loop Count # Backtracking Method # Python

Dynamic programming algorithm reference blogger, the first two have the same time complexity, while the third has relatively lower time complexity
1. Backtracking Algorithm 1:

#loop count #backtracking method 
import math
def backroad(path):
if len(path)==21:
  Length+=1
  return
for num in range(2,22):
  if len(path)==1:
      path.append(num)
      backroad(path,ss)
      path.pop()
  else:
      if num in path or math.gcd(path[-1],num)!=1:
          continue
      path.append(num)
      backroad(path)
      path.pop()
if __name__=='__main__':
Length=[]
backroad([1],0)
print(Length)

2. Pure violence.

#solution 2 for loop counting #pure violence 
import itertools
num=[]
for i in range(2,22):
num.append(i)
data=[]
SS=0
AA=[]
for i in itertools.permutations(num,len(num)):
for j in range(len(num)-1):
  if math.gcd(num[j],num[j+1])!=1:
      break
else:
  AA.append(i)
  SS+=1
print(SS)

3. Backtracking Algorithm 2.

#hash table solving 
import math
Road={}
for i in range(2,22):
for j in range(2,22):
  if i!=j and math.gcd(i,j)==1:
      if i not in Road.keys():
          Road[i]=[j]
      else:
          Road[i].append(j)
def ComBack(path):
global GG
if len(path)==20:
  GG+=1
  print(GG)
  return
for j in Road[path[-1]]:
  if j not in path:
      path.append(j)
      ComBack(path)
      path.pop()
if __name__=='__main__':
GG=0
for i in range(2,22):
  ComBack([i])
print(GG)

Related articles