Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
1 <= n <= 8
class Solution {
List<String> ret = new ArrayList<>();
public List<String> generateParenthesis(int n) {
helper(n, 0 ,0, "");
return ret;
}
public void helper(int n, int open, int close, String s) {
if(s.length() == n*2) {
ret.add(s);
return;
}
if(open<n) helper(n, open+1, close, s+"(");
if(close<open) helper(n, open, close+1, s+")");
}
}
open, close 개수 카운트 사용하여 recursive 돌려버린다.
I found that solution very popular and helpful: https://www.youtube.com/watch?v=N3O1snRqacI&ab_channel=EricProgramming