class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
L = len(words)
ans = 0
def isValid(word, letters):
safe = letters.copy()
localScore = 0
for e in word:
if e in letters:
letters.remove(e)
localScore += score[ord(e) - 97]
else:
return 0, safe
return localScore, letters
def backtrack(index, temp, letters, currentScore):
nonlocal ans
if index >= len(words):
ans = max(ans, currentScore)
return
word = words[index]
backtrack(index + 1, temp, letters.copy(), currentScore)
validScore, changedLetters = isValid(word, letters)
if validScore:
backtrack(index + 1, temp + [word], changedLetters, currentScore + validScore)
for index in range(L):
backtrack(index, [], letters.copy(), 0)
return ans