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