-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_1255.java
54 lines (50 loc) · 1.74 KB
/
leetcode_1255.java
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
class Solution {
public int maxScoreWords(String[] words, char[] letters, int[] score) {
int W = words.length;
// Count how many times each letter occurs
freq = new int[26];
for (char c: letters) {
freq[c - 'a']++;
}
maxScore = 0;
check(W - 1, words, score, new int[26], 0);
return maxScore;
}
// Check if adding this word exceeds the frequency of any letter
private boolean isValidWord(int[] subsetLetters) {
for (int c = 0; c < 26; c++) {
if (freq[c] < subsetLetters[c]) {
return false;
}
}
return true;
}
private int maxScore;
private int[] freq;
private void check(int w, String[] words, int[] score, int[] subsetLetters, int totalScore) {
if (w == -1) {
// If all words have been iterated, check the score of this subset
maxScore = Math.max(maxScore, totalScore);
return;
}
// Not adding words[w] to the current subset
check(w - 1, words, score, subsetLetters, totalScore);
// Adding words[w] to the current subset
int L = words[w].length();
for (int i = 0; i < L; i++) {
int c = words[w].charAt(i) - 'a';
subsetLetters[c]++;
totalScore += score[c];
}
if (isValidWord(subsetLetters)) {
// Consider the next word if this subset is still valid
check(w - 1, words, score, subsetLetters, totalScore);
}
// Rollback effects of this word
for (int i = 0; i < L; i++) {
int c = words[w].charAt(i) - 'a';
subsetLetters[c]--;
totalScore -= score[c];
}
}
}