classSolution:defmaxScoreWords(self,words,letters,score): ans =0defdfs(start, 当前的分数, counter):if start >len(words):return ans =max(ans, cur)for j in 循环start之后的单词:if 如果当前单词加进去还满足游戏规则:dfs(j +1, 新的分数, 新的counter)dfs(0, 0, collections.Counter(letters))return ans
classSolution:defmaxScoreWords(self,words,letters,score): self.ans =0 words_score = [sum(score[ord(c)-ord('a')] for c in word)for word in words] words_counter = [collections.Counter(word)for word in words]defbacktrack(start,cur,counter):if start >len(words):return self.ans =max(self.ans, cur)for j, w_counter inenumerate(words_counter[start:], start):ifall(n <= counter.get(c,0) for c,n in w_counter.items()):backtrack(j+1, cur+words_score[j], counter-w_counter)backtrack(0, 0, collections.Counter(letters))return self.ans