这个问题适合使用递归解决——可能是经典的动态规划,尽管我还没有完全解决它。
你有固定数量的潜在分割点和一定数量的分割要做。你应该能够得到类似以下的东西:
(splits, max_ht, min_ht) = split_list(list, requested_splits,
curr_max, curr_min)
该函数应迭代潜在的分割点,并在列表的其余部分上递归调用自身(请求的分割减少一个)。例如:
def split_list(list, requested_splits, curr_max, curr_min):
best_splits = []
best_split_len = curr_max-curr_min
best_max = curr_max
best_min = curr_min
if requested_splits == 0:
return (best_splits, curr_max, curr_min)
for candidate in candidate_split_points:
this_max = max(curr_max, len(<list up to split point>)
this_min = min(curr_min, len(<list up to split point>)
(splits, new_max, new_min) = split_list(<list after split point>,
requested_splits-1,
this_max, this_min)
if (new_max-new_min) < best_split_len:
best_split_len = new_max - new_min
best_max = new_max
best_min = new_min
best_splits = [candidate] + splits
return (best_splits, best_max, best_min)