我正在尝试制作一些代码,这些代码将采用多维列表并将其转换为字典树。
多维列表可能是这样的。
x = [[0,2,5],[1,1,3],[2,1,1]]
列表将始终代表NxN网格。想象它。
0 2 5
1 1 3
2 1 1
从左上角开始,您只能从节点向右或向下查找其子节点。
So 0 would have children of 2 and 1
2 would have children of 5 and 1
5 would have children of ...
1 would have children of ...
1 would have children of 1 and 2
1 would have children of ...
2 would have children of ...
所以这个树就是这样的:
0
/ \
/ \
/ \
/ \
/ \
2 1
/\ /\
/ \ / \
/ \ / \
1 5 2 1
/\ | | /\
/ \ | | / \
1 3 3 1 3 1
| | | | | |
1 1 1 1 1 1
这是视觉树对节点及其子节点的看法,它将由此结构中的代码表示:
tree = {'value': 0, 'children': [
{'value': 2, 'children': [
{'value': 1, 'children': [
{'value': 1, 'children': [
{'value': 1, 'children': [None, None]}
]},
{'value': 3, 'children': [
{'value': 1, 'children': [None, None]}
]}
]},
{'value': 5, 'children': [
{'value': 3, 'children': [
{'value': 1, 'children': [None, None]}
]}
]}
]},
{'value': 1, 'children': [
{'value': 1, 'children': [
{'value': 3, 'children': [
{'value': 1, 'children': [None, None]}
]},
{'value': 1, 'children': [
{'value': 1, 'children': [None, None]}
]}
]},
{'value': 2, 'children': [
{'value': 1, 'children': [
{'value': 1, 'children': [None, None]}
]}
]}
]}
]}
如果有任何有效的方法可以将上述网格转换为这个形状合理的字典,那么正确的方向指导会非常有帮助。我试过这个:http://repl.it/6sU没有运气,因为递归太深,但是我想不出有不同的方法去做。谢谢。
答案 0 :(得分:1)
我将针对您遇到的实际问题发布解决方案,正如您在评论中提到的那样,找到最接近给定数字的总和,其中通过仅移动NxN矩阵来找到候选总和向下和向右。
def gridsums(grid, x, y, memo):
if memo[x][y] is not None:
return memo[x][y]
if x == 0 and y == 0:
sums = [0]
elif x == 0:
sums = gridsums(grid, x, y-1, memo)
elif y == 0:
sums = gridsums(grid, x-1, y, memo)
else:
sums = gridsums(grid, x-1, y, memo) + gridsums(grid, x, y-1, memo)
sums = [grid[x][y] + s for s in sums]
memo[x][y] = sums
return sums
def gridsumsfast(grid):
memo = []
for row in grid:
memo.append([])
for cell in row:
memo[-1].append(None)
return gridsums(grid, len(grid[0]) - 1, len(grid) - 1, memo)
最简单的版本是完全删除“备忘录”内容,但实现“动态编程”以缓存先前计算的结果并避免重复工作。其余的是一个相当简单的递归解决方案,它直接产生所有可能的总和(包括重复)。
对于您的示例数据,结果为[11, 7, 6, 5, 4, 5]
。