DevPath

← All problems

Count Balanced Parentheses

Medium backtracking · math

Description

Return how many strings of n pairs of parentheses are balanced.

Constraints

0 <= n <= 15

Examples

Input: n = 3

Output: 5

Hints (1)
  • The count is the nth Catalan number: C(2n, n) / (n + 1).

Solutions

Catalan recurrence. · Time O(n) · Space O(1)

func countParentheses(n int) int {
    result := 1
    for i := 0; i < n; i++ {
        result = result * (4*i + 2) / (i + 2)
    }
    return result
}

Create a free account to submit solutions, track progress and save problems.

Create account