Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

https://leetcode.com/problems/generate-parentheses/

 

Generate Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

n쌍의 괄호가 나올 수 있는 경우의 수를 구하는 문제이다.

이런 문제를 접할때 마다 정말. . 이렇게 간단하게 풀어내는 사람들이 신기할 뿐이다. .

List<String> res = new LinkedList();
    public List<String> generateParenthesis(int n) {
        dfs(new StringBuilder(), 0, n);
        return res;
    }
    private void dfs(StringBuilder sb, int close, int n) {
        if(n==0 && close==0) {
            res.add(sb.toString());
            return;
        }

        //Add open parenthese
        if(n>0) {
            sb.append('(');
            dfs(sb, close+1, n-1);
            sb.setLength(sb.length()-1);
        }

        //Add close parenthese
        if(close>0) {
            sb.append(')');
            dfs(sb, close-1, n);
            sb.setLength(sb.length()-1);
        }
    }

참고 코드

+ Recent posts