new_remaining = ''.join(char * new_remaining_counter[char] for char in new_remaining_counter)
出口:remaining word为空,返回0
注意
@lru_cache(None)
```python
from typing import (
List,
)
from collections import Counter
from functools import lru_cache # Import lru_cache
class Solution:
"""
@param stickers: a string array
@param target: a string
@return: the minimum number of stickers that you need to spell out the target
"""
def min_stickers(self, stickers: List[str], target: str) -> int:
# Write your code here
sticker_counters = [Counter(i) for i in stickers]
@lru_cache(None)
def dp(remaining: str) -> int:
if not remaining:
return 0
min_stickers = float('inf')
remaining_counter = Counter(remaining)
for sticker_counter in sticker_counters:
if sticker_counter[remaining[0]] == 0:
continue
new_remaining_counter = remaining_counter-sticker_counter #需要char* 为了防止漏掉重复的char
new_remaining = ''.join(char * new_remaining_counter[char] for char in new_remaining_counter)
min_stickers = min(min_stickers,1+dp(new_remaining))
return min_stickers
result = dp(target)
return result if result != float('inf') else -1
```
```python
from typing import (
List,
)
from collections import deque,Counter
class Solution:
"""
@param stickers: a string array
@param target: a string
@return: the minimum number of stickers that you need to spell out the target
"""
def min_stickers(self, stickers: List[str], target: str) -> int:
# Write your code here
q = deque([0]) #should be a list not a set {}
dist = {0:0}
n = len(target)
final_state = 1<<n # no empty space, NOT 1 >> n
while q:
now = q.popleft()
for sticker in stickers:
sticker_counter = Counter(sticker)
state = now #should initialize to now
for i,c in enumerate(target):
if not now&1<<i and sticker_counter[c] > 0:
state |= 1<<i
sticker_counter[c] -= 1
if state in dist:
continue
q.append(state)
dist[state] = dist[now] + 1
if state == final_state -1:
return dist[state]
return -1
```