【回溯】因为words只有14个,只是放不放的问题,所以最多也就2^14。在回溯的过程中验证letters的个数是否支持当前word加入。
class Solution {
// 30:00 bt
String[] words;
int[] value;
int n, ans;
int[] cnt = new int[26];
public void bt(int t, int s) {
if (t == n) {
ans = Math.max(ans, s);
return;
}
int flag = 1;
String w = words[t];
int[] num = new int[26];
for (int i = 0; i < w.length(); i++) num[w.charAt(i) - 'a']++;
for (int i = 0; i < 26; i++) {
if (num[i] > cnt[i]) {
flag = 0;
break;
}
}
if (flag == 1) {
for (int i = 0; i < 26; i++) {
cnt[i] -= num[i];
}
bt(t + 1, s + value[t]);
for (int i = 0; i < 26; i++) {
cnt[i] += num[i];
}
}
bt(t + 1, s);
}
public int maxScoreWords(String[] words, char[] letters, int[] score) {
this.words = words;
n = words.length;
this.value = new int[n];
for (char l: letters) cnt[l - 'a']++;
for (int i = 0; i < n; i++) {
String w = words[i];
int t = 0;
for (int j = 0; j < w.length(); j++) t += score[w.charAt(j) - 'a'];
value[i] = t;
}
bt(0, 0);
return ans;
}
}