我正在尝试实施动态编程来解决一组25个城市的TSP问题。 通过直接实现程序,我面临“内存错误”。我试图通过考虑我的实现仅需要比当前子集小1的子集来解决它,即动态编程中的子问题是移除了一个元素的当前集合。因此,仅存储对应于当前和先前尺寸的距离(尺寸从2到25变化)。尽管如此,该程序仍占用了近85%的内存然后抛出错误。我的系统有4GB的RAM。 如何修复代码以使其内存使用不会爆炸?
def make_set(i):
'''Generates all subsets of size i(integer)
from cities, including the element 1'''
cities = range(2,26)
subs = comb(cities,i)
for j in subs:
j=set(j)
j.add(1)
yield j
def tsp(cities,dist):
'''Performs search on subsets to find shortest path that traverses
all cities starting and ending at 1
Returns a dictionary, contains all
needs to be processed further to find the subset_dist answer'''
subset_dist={}
subset_dist[(frozenset([1]),1)]=0
for i in range(1,25):
subset_dist_new={}
subsets = make_set(i) #generator for subsets of size i
for S in subsets:
for j in S: # j is the destination
if j!=1:
min_dist= float('inf')
S_minusJ = set(S)
S_minusJ.remove(j)
for k in S: #k defines the subproblem, the closest city before j, for current subset
if k==1 and len(S)>2:
continue
if k!=j:
min_dist = min(min_dist,subset_dist[(frozenset(S_minusJ),k)]+dist[frozenset([j,k])])
subset_dist_new[(frozenset(S),j)] = min_dist
subset_dist = subset_dist_new
return subset_dist_new