Generate balanced brackets up to a depth limit
Coding problemMedium
Given whole numbers n and depth, return every string of n opening brackets ( and n closing brackets ) that is balanced and never nests deeper than depth.
Balanced means every closing bracket closes an earlier opening one, and every opening bracket is closed. The nesting depth at a point is the number of brackets open there; "(())" reaches depth 2 and "()()" stays at depth 1. When depth is at least n, the limit never matters and you get every balanced string. Return the strings in any order.
Examples
Example 1
Input: n = 3, depth = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input: n = 3, depth = 2
Output: ["(()())","(())()","()(())","()()()"]
"((()))" reaches depth 3, so it is left out.
Example 3
Input: n = 2, depth = 1
Output: ["()()"]
Constraints
- 1 <= n <= 10
- 1 <= depth <= 10
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.