算法描述:将1-9放入9个盒子中,使其满足XXX + XXX = XXX,请问有多少种情况(去重)?
算法实现:采用了dfs的核心思想
a = [0] * 9
book = [0] * 9
TOTAL = 0
def dfs(step):
if (step == len(a)):
con1 = a[0] * 100 + a[1] * 10 + a[2]
con2 = a[3] * 100 + a[4] * 10 + a[5]
con3 = a[6] * 100 + a[7] * 10 + a[8]
if ((con1 + con2) == con3):
global TOTAL
TOTAL += 1
print('{0}{1}{2} + {3}{4}{5} = {6}{7}{8}'.format(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]))
return
for i in range(1,10):
if (book[i-1] == 0): # still in hand
a[step] = i
book[i-1] = 1 # not in hand
dfs(step + 1) # Recursive to next step
book[i-1] = 0 # The most important step to take it on hand
if __name__=='__main__':
dfs(0)
#print(TOTAL) #一共有336种可能
print('TOTAL:{0}'.format(TOTAL//2)) #去重过后有168种