สมมติว่าเรามีรายการตัวเลข A, B ต้องเลือก sublist ใน A บางส่วนกลับด้าน (หลายครั้งก็ได้) ดูว่าได้ B หรือไม่
ตัวอย่าง: A = [2, 3, 4, 9, 10], B = [4, 3, 2, 10, 9] → True (กลับ [2,3,4] และ [9,10])
ขั้นตอนการแก้ปัญหา (Frequency Count)
- นับความถี่ใน A และ B ด้วย
Counter - หากความถี่ทุกตัวเท่ากัน → True (เพราะกลับ sublist ได้ทุก permutation)
หมายเหตุ: โจทย์นี้เทียบเท่ากับการตรวจสอบว่า A และ B มี multiset เหมือนกันหรือไม่
ตัวอย่างโค้ด Python
from collections import defaultdict
class Solution:
def solve(self, nums, target):
res = defaultdict(int)
for n in nums:
res[n] += 1
for t in target:
res[t] -= 1
return all(v == 0 for v in res.values())
ob = Solution()
A = [2, 3, 4, 9, 10]
B = [4, 3, 2, 10, 9]
print(ob.solve(A, B)) # Output: True
อินพุต
[2, 3, 4, 9, 10], [4, 3, 2, 10, 9]
เอาต์พุต
True