考虑需要两行的情况。您可以只测试列表中所有可能的分割点(索引),看看哪一个产生最好的结果(最小化最大行宽)。
对于超过两行,只需使用递归继续拆分“右半部分”,如下面的代码示例所示。(Python)
def split(sizes, count):
# base case: one row, just return it
if count == 1:
return [sizes]
best_score = None
best_result = None
# for each possible split point (don't allow empty rows)
for i in range(1, len(sizes)):
# the first row is the columns up to the split point
left = [sizes[:i]]
# recurse to process the remaining rows
right = split(sizes[i:], count - 1)
if right is None:
# failed to split count - 1 times, ignore
continue
rows = left + right
# minimize the maximum row width
score = max(sum(row) for row in rows)
if best_score is None or score < best_score:
best_score = score
best_result = rows
return best_result
if __name__ == '__main__':
sizes = [100, 50, 100, 50, 50, 50]
print split(sizes, 2)
print split(sizes, 3)
输出:
[[100, 50], [100, 50, 50, 50]] # 2 rows
[[100], [50, 100], [50, 50, 50]] # 3 rows