抱歉,如果之前有人问过这个问题,但我已经搜索了好几天,但没有找到与我的问题相关的帮助。
我正在尝试研究的是一种解析列表(类似于预算表)并将索引分配给父母或孩子的方法。父级是其子级的总和,而子级是该父级(或没有父级的数字)的加数。
例如:[1,2,3,6],其中 6 是 1、2 和 3 的父级。
或更复杂的例子[1,2,3,6,1,4,3,8,14,3,2,3,8,1,4,3,8,16,30]:
30 是这个列表的“根”,因为 30 = 14 + 16、14 = 6 + 8、6 = 1 + 2 + 3 等等。这个列表总是有点顺序的,即孩子总是一起出现在他们的父母之前(当然,当父母是另一位父母的孩子时除外)。我试图找到最有效的方法,我的 2 个解决方案使用堆栈,但它们并不是 100% 正确,因为上面的 2 个示例失败了。这是两者的伪代码:
解决方案尝试 1
stack = []
for number in list
if stack.isEmpty()
stack.push(number)
elif stack.peek() > number
stack.push(number)
else
copy = stack
temp = []
current = number
while current > 0
popped = copy.pop()
temp.push(popped)
current -= popped
if current == 0
while temp
child = temp.pop()
child.parent = number
stack = copy
stack.push(number)
解决方案尝试 2
stack = []
for number in list
stack.push(number)
while stack.size() > 1
child = stack.pop()
copy = stack
temp = []
if child > stack.peek()
while current > 0 and copy.size() > 0
popped = copy.pop()
temp.push(popped)
current -= popped
if current == 0
while temp
child = temp.pop()
child.parent = number
任何想法或想法将不胜感激。在这一点上,我正在用头撞墙。
编辑
复杂示例解决方案
[1,2,3,6,1,4,3,8,14,3,2,3,8,1,4,3,8,16,30]
30
/ \
14 16
/ \ / \
6 8 8 8
/ | \ / | \ / | \ / | \
1 2 3 1 4 3 3 2 3 1 4 3