Return every balanced string you can make from n pairs of parentheses, in any order. Balanced means every ( is closed by a ) that comes after it, and no ) appears before its matching (.
generateParentheses(2) returns ["(())", "()()"].
This is a backtracking problem, like N-Queens: build the string one character at a time, and only add a character when the string can still end up balanced.
n is between 1 and 8.
Input: generateParentheses(2)
Output: ["(())", "()()"]
Input: generateParentheses(3)
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Your solution is checked against 2 example tests and 4 hidden tests (edge cases and bigger inputs).
Languages you don't learn in class are worth more: C++ 1.25×, JavaScript, TypeScript, C, Rust and Go 1.5×. Your first solve in a language unlocks its "Learned" achievement: +25 for learning it.
Loading editor...
Run Code checks the example tests. Submit runs every test, including hidden ones.