- 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
- 39 lines of C++ from the credited upstream file 1467.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block 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.
1enum class BoxCase { kEqualBalls, kEqualDistantBalls };2 3class Solution {4 public:5 double getProbability(vector<int>& balls) {6 const int n = accumulate(balls.begin(), balls.end(), 0) / 2;7 return cases(balls, 0, 0, 0, 0, 0, n, BoxCase::kEqualDistantBalls) /8 cases(balls, 0, 0, 0, 0, 0, n, BoxCase::kEqualBalls);9 }10 11 private:12 const vector<int> fact{1, 1, 2, 6, 24, 120, 720};13 14 15 double cases(const vector<int>& balls, int i, int ballsCountA,16 int ballsCountB, int colorsCountA, int colorsCountB, int n,17 BoxCase boxCase) {18 if (ballsCountA > n || ballsCountB > n)19 return 0;20 if (i == balls.size())21 return boxCase == BoxCase::kEqualBalls ? 1 : colorsCountA == colorsCountB;22 23 double ans = 0;24 25 26 for (int ballsTakenA = 0; ballsTakenA <= balls[i]; ++ballsTakenA) {27 const int ballsTakenB = balls[i] - ballsTakenA;28 const int newcolorsCountA = colorsCountA + (ballsTakenA > 0);29 const int newcolorsCountB = colorsCountB + (ballsTakenB > 0);30 ans += cases(balls, i + 1, ballsCountA + ballsTakenA,31 ballsCountB + ballsTakenB, newcolorsCountA, newcolorsCountB,32 n, boxCase) /33 (fact[ballsTakenA] * fact[ballsTakenB]);34 }35 36 return ans;37 }38};39