栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

数组的N折分区,每个分区中的总和相等

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数组的N折分区,每个分区中的总和相等

这是我自己的使用动态编程的Python解决方案。这里给出算法。

def get_subset(lst, s):    '''Given a list of integer `lst` and an integer s, returns    a subset of lst that sums to s, as well as lst minus that subset    '''    q = {}    for i in range(len(lst)):        for j in range(1, s+1): if lst[i] == j:     q[(i, j)] = (True, [j]) elif i >= 1 and q[(i-1, j)][0]:     q[(i, j)] = (True, q[(i-1, j)][1]) elif i >= 1 and j >= lst[i] and q[(i-1, j-lst[i])][0]:     q[(i, j)] = (True, q[(i-1, j-lst[i])][1] + [lst[i]]) else:     q[(i, j)] = (False, [])        if q[(i, s)][0]: for k in q[(i, s)][1]:     lst.remove(k) return q[(i, s)][1], lst    return None, lstdef get_n_subset(n, lst, s):    ''' Returns n subsets of lst, each of which sums to s'''    solutions = []    for i in range(n):        sol, lst = get_subset(lst, s)        solutions.append(sol)    return solutions, lst# print(get_n_subset(7, [1, 2, 3, 4, 5, 7, 8, 4, 1, 2, 3, 1, 1, 1, 2], 5))# [stdout]: ([[2, 3], [1, 4], [5], [4, 1], [2, 3], [1, 1, 1, 2], None], [7, 8])


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660480.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号