Problem solution · C++

Handshakes That Dont Cross

Handshakes That Dont Cross: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
58 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Handshakes That Dont Cross, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeHandshakes That Dont Cross · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n)// Space: O(1) class Solution {public:    int numberOfWays(int num_people) {        static const int MOD = 1e9 + 7;        int n = num_people / 2;        return 1ULL * nCr(2 * n, n, MOD) * inv(n + 1, MOD) % MOD;  // Catalan number    }    private:    int nCr(int n, int k, int m) {        if (n - k < k) {            return nCr(n, n - k, m);        }        uint64_t result = 1;        for (int i = 1; i <= k; ++i) {            result = (result * (n - k + i) % m) * inv(i, m) % m;        }        return result;    }        int inv(int x, int m) {  // Euler's Theorem        return pow(x, m - 2, m);    }     int pow(uint64_t a, int b, int m) {  // O(logMOD) = O(1)        a %= m;        uint64_t result = 1;        while (b) {            if (b & 1) {                result = (result * a) % m;            }            a = (a * a) % m;            b >>= 1;        }        return result;    }}; // Time:  O(n^2)// Space: O(n)class Solution2 {public:    int numberOfWays(int num_people) {        static const int MOD = 1e9 + 7;        vector<uint64_t> dp(num_people / 2 + 1);        dp[0] = 1ULL;        for (int k = 1; k <= num_people / 2; ++k) {            for (int i = 0; i < k; ++i) {                dp[k] = (dp[k] + dp[i] * dp[k - 1 - i]) % MOD;            }        }        return dp[num_people / 2];    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗