- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 71 lines of C++ from the credited upstream file 3317.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 numberOfWays(int n, int x, int y) {4 const int maxStages = min(n, x);5 const auto [fact, invFact] = getFactAndInvFact(max(n, x));6 const vector<vector<int>> stirling = getStirling(n, maxStages);7 int ans = 0;8 9 for (int k = 1; k <= maxStages; ++k) {10 11 long events = nCk(x, k, fact, invFact);12 13 events = events * stirling[n][k] % kMod;14 15 events = events * fact[k] % kMod;16 17 events = events * modPow(y, k) % kMod;18 ans = (ans + events) % kMod;19 }20 21 return ans;22 }23 24 private:25 static constexpr int kMod = 1'000'000'007;26 27 pair<vector<long>, vector<long>> getFactAndInvFact(int n) {28 vector<long> fact(n + 1);29 vector<long> invFact(n + 1);30 vector<long> inv(n + 1);31 fact[0] = invFact[0] = 1;32 inv[0] = inv[1] = 1;33 for (int i = 1; i <= n; ++i) {34 if (i >= 2)35 inv[i] = kMod - kMod / i * inv[kMod % i] % kMod;36 fact[i] = fact[i - 1] * i % kMod;37 invFact[i] = invFact[i - 1] * inv[i] % kMod;38 }39 return {fact, invFact};40 }41 42 int nCk(int n, int k, const vector<long>& fact, const vector<long>& invFact) {43 return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod;44 }45 46 47 48 49 50 vector<vector<int>> getStirling(int n, int k) {51 vector<vector<int>> stirling(n + 1, vector<int>(k + 1));52 stirling[0][0] = 1;53 for (int i = 1; i <= n; ++i) {54 stirling[i][1] = 1;55 for (int j = 2; j <= min(i, k); ++j)56 stirling[i][j] = (static_cast<long>(j) * stirling[i - 1][j] +57 stirling[i - 1][j - 1]) %58 kMod;59 }60 return stirling;61 }62 63 long modPow(long x, long n) {64 if (n == 0)65 return 1;66 if (n % 2 == 1)67 return x * modPow(x % kMod, (n - 1)) % kMod;68 return modPow(x * x % kMod, (n / 2)) % kMod;69 }70};71