|
| 1 | +classSolution { |
| 2 | +publicintmaxScoreWords(String[]words,char[]letters,int[]score) { |
| 3 | +int[]letterCount =newint[26]; |
| 4 | +for (charletter :letters) { |
| 5 | +letterCount[letter -'a'] +=1; |
| 6 | + } |
| 7 | +returnbacktrack(0,words,score,letterCount); |
| 8 | + } |
| 9 | + |
| 10 | +privateintbacktrack(inti,String[]words,int[]score,int[]letterCount) { |
| 11 | +if (i ==words.length) { |
| 12 | +return0; |
| 13 | + } |
| 14 | +intres =backtrack(i +1,words,score,letterCount); |
| 15 | +Stringword =words[i]; |
| 16 | +if (canFormWord(word,letterCount)) { |
| 17 | +for (charch :word.toCharArray()) { |
| 18 | +letterCount[ch -'a'] -=1; |
| 19 | + } |
| 20 | +res =Math.max(res,getScore(word,score) +backtrack(i +1,words,score,letterCount)); |
| 21 | +for (charch :word.toCharArray()) { |
| 22 | +letterCount[ch -'a'] +=1; |
| 23 | + } |
| 24 | + } |
| 25 | +returnres; |
| 26 | + } |
| 27 | + |
| 28 | +privatebooleancanFormWord(Stringword,int[]letterCount) { |
| 29 | +int[]wordCount =newint[26]; |
| 30 | +for (charch :word.toCharArray()) { |
| 31 | +wordCount[ch -'a'] +=1; |
| 32 | + } |
| 33 | +for (inti =0;i <26;i++) { |
| 34 | +if (wordCount[i] >letterCount[i]) { |
| 35 | +returnfalse; |
| 36 | + } |
| 37 | + } |
| 38 | +returntrue; |
| 39 | + } |
| 40 | + |
| 41 | +privateintgetScore(Stringword,int[]score) { |
| 42 | +inttotal =0; |
| 43 | +for (charch :word.toCharArray()) { |
| 44 | +total +=score[ch -'a']; |
| 45 | + } |
| 46 | +returntotal; |
| 47 | + } |
| 48 | +} |