Interview questions, please answer
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>
Result:
<code>22</code>
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>