- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 54 lines of C++ from the credited upstream file 3333.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 possibleStringCount(string word, int k) {4 const vector<int> groups = getConsecutiveLetters(word);5 const int totalCombinations =6 accumulate(groups.begin(), groups.end(), 1L,7 [](long acc, int group) { return acc * group % kMod; });8 if (k <= groups.size())9 return totalCombinations;10 11 12 13 vector<int> dp(k);14 dp[0] = 1; 15 16 for (int i = 0; i < groups.size(); ++i) {17 vector<int> newDp(k);18 int windowSum = 0;19 int group = groups[i];20 for (int j = i; j < k; ++j) {21 newDp[j] = (newDp[j] + windowSum) % kMod;22 windowSum = (windowSum + dp[j]) % kMod;23 if (j >= group)24 windowSum = (windowSum - dp[j - group] + kMod) % kMod;25 }26 dp = std::move(newDp);27 }28 29 const int invalidCombinations =30 accumulate(dp.begin(), dp.end(), 0,31 [](int acc, int count) { return (acc + count) % kMod; });32 return (totalCombinations - invalidCombinations + kMod) % kMod;33 }34 35 private:36 static constexpr int kMod = 1'000'000'007;37 38 39 40 vector<int> getConsecutiveLetters(const string& word) {41 vector<int> groups;42 int group = 1;43 for (int i = 1; i < word.length(); ++i)44 if (word[i] == word[i - 1]) {45 ++group;46 } else {47 groups.push_back(group);48 group = 1;49 }50 groups.push_back(group);51 return groups;52 }53};54