Interview questions, please answer interview questions, please answer
Reply content:
Interview questions, please answer
Typical 3Sum, leetcode on the original question https://leetcode.com/problems...
JavaScript can look at my problem https://github.com/hanzichi/l...
This question is also the title of the introduction of old Zhao and winter handwritten questions, you can see the https://zhuanlan.zhihu.com/p...
The best method seems to be O (n ^ 2 ).
Are all determined to be 3 integers ...... Triplicate loop enumeration ............
As @ xiaoboost said, the violence against the statement can be made:
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))
Result:
22
Questions I have answered: 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])