- 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
- 58 lines of C++ from the credited upstream file handshakes-that-dont-cross.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 4 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.
123 4class Solution {5public:6 int numberOfWays(int num_people) {7 static const int MOD = 1e9 + 7;8 int n = num_people / 2;9 return 1ULL * nCr(2 * n, n, MOD) * inv(n + 1, MOD) % MOD; 10 }11 12private:13 int nCr(int n, int k, int m) {14 if (n - k < k) {15 return nCr(n, n - k, m);16 }17 uint64_t result = 1;18 for (int i = 1; i <= k; ++i) {19 result = (result * (n - k + i) % m) * inv(i, m) % m;20 }21 return result;22 }23 24 int inv(int x, int m) { 25 return pow(x, m - 2, m);26 }27 28 int pow(uint64_t a, int b, int m) { 29 a %= m;30 uint64_t result = 1;31 while (b) {32 if (b & 1) {33 result = (result * a) % m;34 }35 a = (a * a) % m;36 b >>= 1;37 }38 return result;39 }40};41 424344class Solution2 {45public:46 int numberOfWays(int num_people) {47 static const int MOD = 1e9 + 7;48 vector<uint64_t> dp(num_people / 2 + 1);49 dp[0] = 1ULL;50 for (int k = 1; k <= num_people / 2; ++k) {51 for (int i = 0; i < k; ++i) {52 dp[k] = (dp[k] + dp[i] * dp[k - 1 - i]) % MOD;53 }54 }55 return dp[num_people / 2];56 }57};58