Skip to content

Commit

Permalink
Create 05. Stickers to Spell Word.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb committed Jan 31, 2023
1 parent fc43c50 commit 29578bd
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 02_Dynamic-Programming/05. Stickers to Spell Word.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# https://leetcode.com/problems/stickers-to-spell-word/
# https://youtu.be/hsomLb6mUdI

class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
targetSet = set(target)
stickCount = []
for s in stickers:
stick = {}
for i in s:
if i in targetSet:
stick[i] = stick.get(i, 0) + 1
stickCount.append(stick)

dp = {}
def dfs(t, stick):
if t in dp:
return dp[t]
res = 1 if stick else 0
remainT = ""
for c in t:
if c in stick and stick[c] > 0:
stick[c] -= 1
else:
remainT += c

if remainT:
used = 2**31
for stick in stickCount:
if remainT[0] not in stick:
continue
used = min(used, dfs(remainT, stick.copy()))
dp[remainT] = used
res += used
return res

res = dfs(target, {})
return res if res != 2**31 else -1



# Time: O(2^n)

0 comments on commit 29578bd

Please sign in to comment.