LeetCode 1259: Handshakes That Don't Cross

LeetCode 1259 Solution Explanation

Explanation:

The problem asks us to find the number of ways to perform handshakes between people such that no two handshakes cross each other. This can be modeled as finding the number of ways to pair up n people where each person shakes hands with exactly one other person in a non-crossing way.

To solve this problem, we can use dynamic programming. Let's define a function dp[i] which represents the number of ways to pair up i people without any crossing handshakes. We can build up this function iteratively starting from i=2 up to n.

For each i, we can iterate over all possible ways to split the i people into two groups, and then recursively calculate the number of ways to pair up those two groups. The total number of ways for i people can be obtained by summing up the product of the number of ways for the two groups.

The base cases would be dp[0] = 1 and dp[2] = 1 since there is only one way to pair up 2 people without crossing. :

LeetCode 1259 Solutions in Java, C++, Python

class Solution {
    public int numberOfWays(int n) {
        long[] dp = new long[n + 1];
        dp[0] = 1;
        dp[2] = 1;
        
        for (int i = 4; i <= n; i += 2) {
            for (int j = 0; j < i; j += 2) {
                dp[i] += dp[j] * dp[i - j - 2];
                dp[i] %= 1000000007;
            }
        }
        
        return (int)dp[n];
    }
}

Interactive Code Editor for LeetCode 1259

Improve Your LeetCode 1259 Solution

Use the editor below to refine the provided solution for LeetCode 1259. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems