class Solution(object):
    def maxScoreWords(self, words, letters, score):
        """
        :type words: List[str]
        :type letters: List[str]
        :type score: List[int]
        :rtype: int
        """
        from collections import defaultdict, Counter
        dic = dict()
        letter_dic = defaultdict(int)
        for i, val in enumerate(score):#һֵ
            dic[chr(ord("a") + i)] = val #key ĸvalĸӦķ
            
        letter_dic = Counter(letters)#һֵ䣬 keyĸ valÿĸʣĸ
 
        s = set(letters)
        v_words = []
        for word in words:#ɾиܱɵĵ
            flag = 0
            for char in word:
                if char not in s:
                    flag = 1
            if flag: # һĳlettersҲĸ迼
                continue
            v_words.append(word)
        self.res = 0
                
        def helper(word, letter_dic):
            # return True wordletter_dicletterɣ򷵻False
            dicc = collections.Counter(word)
            for key in dicc:
                if dicc[key] > letter_dic[key]:
                    return False
            return True
        
        def dfs(start, tmp):
            self.res = max(self.res, tmp)
            if start >= len(v_words):
                return
            
            for i in range(start, len(v_words)):#startʼңظ
                if helper(v_words[i], letter_dic):#ǰʿԱ
                    for char in v_words[i]: #ֵ
                        letter_dic[char] -= 1
                    dfs(i + 1, tmp + sum([dic[char] for char in v_words[i]])) #dfsһ
                    for char in v_words[i]: #ݣԭ״̬
                        letter_dic[char] += 1                   
        dfs(0, 0)
        return self.res