class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
sticker_count=[Counter(s) for s in stickers]
@cache
def dp(remain):
if not remain:return 0
remain_count=Counter(remain)
res=float('inf')
for count in sticker_count:
if count[remain[0]] == 0:
continue
new_remain=[]
for ch in remain_count:
if remain_count[ch]>count[ch]:
new_remain.append(ch*(remain_count[ch]-count[ch]))
new_remain=''.join(new_remain)
res=min(res,dp(new_remain)+1)
return res
result=dp(target)
return result if result!=float('inf') else -1
if count[remain[0]] == 0:continue
这是非常重要的剪枝,如果当前不含首字母,至少这一次不可能是最优解