[Leetcode] 22. Generate Parentheses (JAVA)

유존돌돌이·2021년 9월 6일
0

Leetcode

목록 보기
10/17
post-thumbnail

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: ["()"]

Constraints

1 <= n <= 8

My Code

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+")");
    }
}

Comment

open, close 개수 카운트 사용하여 recursive 돌려버린다.

1개의 댓글

comment-user-thumbnail
2021년 12월 21일

I found that solution very popular and helpful: https://www.youtube.com/watch?v=N3O1snRqacI&ab_channel=EricProgramming

답글 달기