|
| 1 | +class Solution { |
| 2 | + public int maxScoreWords(String[] words, char[] letters, int[] score) { |
| 3 | + int[] letterCount = new int[26]; |
| 4 | + for (char letter : letters) { |
| 5 | + letterCount[letter - 'a'] += 1; |
| 6 | + } |
| 7 | + return backtrack(0, words, score, letterCount); |
| 8 | + } |
| 9 | + |
| 10 | + private int backtrack(int i, String[] words, int[] score, int[] letterCount) { |
| 11 | + if (i == words.length) { |
| 12 | + return 0; |
| 13 | + } |
| 14 | + int res = backtrack(i + 1, words, score, letterCount); |
| 15 | + String word = words[i]; |
| 16 | + if (canFormWord(word, letterCount)) { |
| 17 | + for (char ch : word.toCharArray()) { |
| 18 | + letterCount[ch - 'a'] -= 1; |
| 19 | + } |
| 20 | + res = Math.max(res, getScore(word, score) + backtrack(i + 1, words, score, letterCount)); |
| 21 | + for (char ch : word.toCharArray()) { |
| 22 | + letterCount[ch - 'a'] += 1; |
| 23 | + } |
| 24 | + } |
| 25 | + return res; |
| 26 | + } |
| 27 | + |
| 28 | + private boolean canFormWord(String word, int[] letterCount) { |
| 29 | + int[] wordCount = new int[26]; |
| 30 | + for (char ch : word.toCharArray()) { |
| 31 | + wordCount[ch - 'a'] += 1; |
| 32 | + } |
| 33 | + for (int i = 0; i < 26; i++) { |
| 34 | + if (wordCount[i] > letterCount[i]) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + private int getScore(String word, int[] score) { |
| 42 | + int total = 0; |
| 43 | + for (char ch : word.toCharArray()) { |
| 44 | + total += score[ch - 'a']; |
| 45 | + } |
| 46 | + return total; |
| 47 | + } |
| 48 | +} |
0 commit comments