回溯法的演算法框架
阿新 • • 發佈:2019-02-12
回溯法
子集樹
程式碼如下:
def constraint():
# 約束函式
return True
def bound():
# 限界函式
return True
def backtracing(t, lst, temp):
# 回溯法函式
size = len(lst)
if t == size:
print(temp)
else:
for i in range(0, size):
temp[t] = lst[i]
if constraint() and bound():
backtracing(t+1, lst, temp) # 遞迴
if __name__ == '__main__':
A = ['A', 'B', 'C']
B = ['A', 'B', 'C']
backtracing(0, A, B)
執行結果:
排列樹
程式碼如下:
def constraint():
# 約束函式
return True
def bound():
# 限界函式
return True
def backtracing(t, lst):
# 回溯法函式
size = len(lst)
if t == size:
print(lst)
else:
for i in range(t, size):
(A[t], A[i]) = (A[i], A[t]) # 交換第i個
if constraint() and bound():
backtracing(t+1, lst)
(A[t], A[i]) = (A[i], A[t])
if __name__ == '__main__' :
A = ['A', 'B', 'C']
backtracing(0, A)
輸出結果: