max_score_word_letters.py (3579B)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | # 1255. Maximum Score Words Formed by Letters """ given a list of 'words' list of single 'letters' (potentially repeating), and 'score' of every character. return the maximum score of any valid set of words formed by using the given letters ('words[i]' cannot be used two or more times). it is not necessary to use all characters in 'letters' and each letter can only be used once. score of letters a through z is given by 'score[i]' respectively. """ class Solution(object): def maxScoreWords(self, words, letters, score): """ :type words: List[str] :type letters: List[str] :type score: List[int] :rtype: int """ cnt = [0] * 26 letters_cnt = [0] * 26 for c in letters: cnt[ord(c) - ord("a")] += 1 self.ans = 0 self.backtracking(words, score, cnt, letters_cnt, 0, 0) return self.ans def backtracking(self, words, score, cnt, letters_cnt, pos, tmp): for i in range(26): if letters_cnt[i] > cnt[i]: return self.ans = max(self.ans, tmp) for i in range(pos, len(words)): for c in words[i]: letters_cnt[ord(c) - ord("a")] += 1 tmp += score[ord(c) - ord("a")] self.backtracking(words, score, cnt, letters_cnt, i + 1, tmp) for c in words[i]: letters_cnt[ord(c) - ord("a")] -= 1 tmp -= score[ord(c) - ord("a")] if __name__ == "__main__": obj = Solution() print( obj.maxScoreWords( words=["dog", "cat", "dad", "good"], letters=["a", "a", "c", "d", "d", "d", "g", "o", "o"], score=[ 1, 0, 9, 5, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], ) ) print( obj.maxScoreWords( words=["xxxz", "ax", "bx", "cx"], letters=["z", "a", "b", "c", "x", "x", "x"], score=[ 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 10, ], ) ) print( obj.maxScoreWords( words=["leetcode"], letters=["l", "e", "t", "c", "o", "d"], score=[ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ], ) ) |