-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1255. Maximum Score Words Formed by Letters.cpp
57 lines (57 loc) · 2.01 KB
/
1255. Maximum Score Words Formed by Letters.cpp
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
class Solution {
public:
int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) {
int W = words.size();
maxScore = 0;
freq = vector<int>(26, 0);
vector<int> subsetLetters = vector<int>(26, 0);
// Count how many times each letter occurs
for (char c : letters) {
freq[c - 'a']++;
}
check(W - 1, words, score, subsetLetters, 0);
return maxScore;
}
private:
int maxScore;
vector<int> freq;
// Check if adding this word exceeds the frequency of any letter
bool isValidWord(vector<int>& subsetLetters) {
for (int c = 0; c < 26; c++) {
if (freq[c] < subsetLetters[c]) {
return false;
}
}
return true;
}
void check(int w, vector<string>& words, vector<int>& score, vector<int>& subsetLetters, int totalScore) {
if (w == -1) {
// If all words have been iterated, check the score of this subset
maxScore = 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][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][i] - 'a';
subsetLetters[c]--;
totalScore -= score[c];
}
}
};