程序查找子列表的数量,这些子列表的总和是python中的目标
假设我们有一个称为nums的数字列表和另一个目标值,我们必须找到总和与目标值相同的子列表的数量。
因此,如果输入类似于nums=[3,0,3]target=3,则输出将为4,因为我们拥有这些子列表的和为3:[3],[3、0],[0,3],[3]。
为了解决这个问题,我们将按照以下步骤操作:
temp:=一个空的map
temp[0]:=1
s:=0
回答:=0
对于范围从0到nums的i,执行
ans:=ans+temp[comp]
s:=s+数字[i]
comp:=s-目标
如果comp处于临时状态,则
temp[s]:=temp[s]+1
返回ans
让我们看下面的实现以更好地理解:
范例程式码
from collections import defaultdict
class Solution:
def solve(self, nums, target):
temp = defaultdict(int)
temp[0] = 1
s = 0
ans = 0
for i in range(len(nums)):
s += nums[i]
comp = s - target
if comp in temp:
ans += temp[comp]
temp[s] += 1
return ans
ob = Solution()nums = [3, 0, 3]
target = 3
print(ob.solve(nums, target))输入值
[3, 0, 3], 3
输出结果
4
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短