首页 > 有一个数组,从中挑ABC三个整数,让ABC三个整数加起来等于0,看有多少个这样的数组?

有一个数组,从中挑ABC三个整数,让ABC三个整数加起来等于0,看有多少个这样的数组?

面试题,求解答


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])

典型的 3Sum,leetcode 上有原题 https://leetcode.com/problems...

JavaScript 可以看下我的题解 https://github.com/hanzichi/l...

这道题也是职人介绍所老赵和 winter 手写的题,可以看下 https://zhuanlan.zhihu.com/p/...

最好的方法貌似是 O(n^2) 的两边逼进


都确定是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

【热门文章】
【热门文章】