javascript - There is an array, pick three integers ABC from it, and let the sum of the three integers ABC equal 0. How many such arrays are there?

WBOY
Release: 2016-08-20 09:04:06
Original
1005 people have browsed it

Interview questions, please answer

Reply content:

Interview questions, please answer

Typical 3Sum, the original question is available on leetcode https://leetcode.com/problems...

JavaScript, you can check out my solution https://github.com/hanzichi/l...

This question is also handwritten by Mr. Zhao and Winter from the Job Creation Agency. You can check it out at https://zhuanlan.zhihu.com/p/...

The best method seems to be O(n^2) two-sided forcing

It’s all confirmed to be 3 integers...just do the triple loop enumeration...

As @xiaoboost said, it can be done using simple brute force methods:

<code class="python">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))</code>
Copy after login

Result:

<code>22</code>
Copy after login

Questions I answered: Python-QA

<code class="python">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])</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template