Mô tả bài toán
Cho danh sách số nums và giá trị target. Đếm số lượng danh sách con (sublist) liên tiếp có tổng bằng target.
Ví dụ: nums = [3, 0, 3], target = 3 → đầu ra 4 (các danh sách con: [3], [3,0], [0,3], [3]).
Giải thuật (Prefix Sum + Hash Map)
- Khởi tạo
templà defaultdict(int), đặttemp[0] = 1. s = 0,ans = 0.- Duyệt qua từng phần tử
nums[i]:s += nums[i].comp = s - target.- Nếu
compcó trongtemp:ans += temp[comp]. temp[s] += 1.
- Trả về
ans.
Ví dụ mã Python
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))
Đầu vào
[3, 0, 3], 3
Đầu ra
4