面试题,求解答
如同 @xiaoboost 說的, 使用簡單的暴力法就可以做出來:
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))
結果:
22
我回答過的問題: Python-QA
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])
10 回答11.1k 阅读
15 回答8.4k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
8 回答6.2k 阅读
2 回答2.6k 阅读✓ 已解决
典型的 3Sum,leetcode 上有原题 https://leetcode.com/problems...
JavaScript 可以看下我的题解 https://github.com/hanzichi/l...
这道题也是职人介绍所老赵和 winter 手写的题,可以看下 https://zhuanlan.zhihu.com/p/...
最好的方法貌似是 O(n^2) 的两边逼进