JavaScript-there is an array from which to pick ABC three integers, so that the ABC three integers equals 0, see how many such arrays?

Source: Internet
Author: User
Interview questions, ask for answers

Reply content:

Interview questions, ask for answers

Typical 3sum,leetcode have the original problem https://leetcode.com/problems ...

JavaScript can look at my https://github.com/hanzichi/l ...

This problem is also the staff of the introduction of the Lao Zhao and winter handwritten questions, you can see the https://zhuanlan.zhihu.com/p/...

The best approach seems to be that both sides of O (n^2) are forced into

are sure to be 3 integers ... Direct Triple-Loop enumeration ah .....

As @xiaoboost says, the simple act of violence can be used:

import itertoolsdef nsum(lst, n, target):    count = 0    for c in itertools.combinations(lst, n):        if sum(c) == target:            count += 1    return countif __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))

Results:

22

I answered the question: Python-qa

from itertools import combinationsdef sum_is_sth(lst, sth=0, cnt=3):    return sum([1 for sub_lst in combinations(lst, cnt) if sum(sub_lst) == sth])
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.