You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单个Python函数高效生成和为n的正整数递增组合

生成和为n的正整数递增组合的高效实现

需求

编写一个接收正整数n(n>0)的函数,返回所有和为n的正整数递增组合。

原实现及问题

尝试用单个函数结合itertools.combinations_with_replacement实现,代码如下:

def all_combinations_sum_to_n(n):
    from itertools import combinations_with_replacement

    combinations_list = []

    if n < 1:
        return combinations_list

    l = [i for i in range(1, n + 1)]
    for i in range(1, n + 1):
        combinations_list = combinations_list + (list(combinations_with_replacement(l, i)))

    result = [list(i) for i in combinations_list if sum(i) == n]
    result.sort()
    return result

但当传入n=20时,因时空复杂度过高(推测为O(n*n!))被系统终止进程。

优化要求

需在仅使用单个函数的前提下,优化代码以提升时空效率。

测试结果更新

经perfpy平台Python3.8测试对比,ShadowRanger的方案在多组n值测试中性能最优。


内容的提问来源于stack exchange,提问作者plpm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:30:36