Approach
Depth-first search
For Maximum Score Words Formed by Letters, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 42 lines of C++ from the credited upstream file 1255.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maxScoreWords(vector<string>& words, vector<char>& letters,4 vector<int>& score) {5 vector<int> count(26);6 for (const char c : letters)7 ++count[c - 'a'];8 return dfs(words, 0, count, score);9 }10 11 private:12 13 int dfs(const vector<string>& words, int s, vector<int>& count,14 const vector<int>& score) {15 int ans = 0;16 for (int i = s; i < words.size(); ++i) {17 const int earned = useWord(words, i, count, score);18 if (earned > 0)19 ans = max(ans, earned + dfs(words, i + 1, count, score));20 unuseWord(words, i, count);21 }22 return ans;23 }24 25 int useWord(const vector<string>& words, int i, vector<int>& count,26 const vector<int>& score) {27 bool isValid = true;28 int earned = 0;29 for (const char c : words[i]) {30 if (--count[c - 'a'] < 0)31 isValid = false;32 earned += score[c - 'a'];33 }34 return isValid ? earned : -1;35 }36 37 void unuseWord(const vector<string>& words, int i, vector<int>& count) {38 for (const char c : words[i])39 ++count[c - 'a'];40 }41};42