4 个回答

都确定是3个整数了……直接三重循环枚举啊…………

如同 @xiaoboost 說的, 使用簡單的暴力法就可以做出來:

import itertools

def nsum(lst, n, target):
    count = 0
    for c in itertools.combinations(lst, n):
        if sum(c) == target:
            count += 1
    return count


if __name__ == '__main__':
    lst = [-1, 3, -2, 7, -4, -3, 6, 9, -2, -2, 1, 1, 0, 10, -1, 9, 8, -12]
    print(nsum(lst, 3, 0))

結果:

22

我回答過的問題: Python-QA

from itertools import combinations

def sum_is_sth(lst, sth=0, cnt=3):
    return sum([1 for sub_lst in combinations(lst, cnt) if sum(sub_lst) == sth])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题