Count Balanced Parentheses
Medium backtracking · math
Description
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
}
Catalan recurrence. · Time O(n) · Space O(1)
function countParentheses(n) {
let result = 1;
for (let i = 0; i < n; i++) {
result = (result * (4 * i + 2)) / (i + 2);
}
return Math.round(result);
}
Catalan recurrence. · Time O(n) · Space O(1)
function countParentheses($n) {
$result = 1;
for ($i = 0; $i < $n; $i++) {
$result = intdiv($result * (4 * $i + 2), $i + 2);
}
return $result;
}
Catalan recurrence. · Time O(n) · Space O(1)
def countParentheses(n):
result = 1
for i in range(n):
result = result * (4 * i + 2) // (i + 2)
return result
Catalan recurrence. · Time O(n) · Space O(1)
function countParentheses(n: number): number {
let result = 1;
for (let i = 0; i < n; i++) {
result = (result * (4 * i + 2)) / (i + 2);
}
return Math.round(result);
}
Create a free account to submit solutions, track progress and save problems.
Create account