JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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

Code

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if(n <= 0) return res;
        
        helper(res, n, n, "");
        return res;
    }
    
    private void helper(List<String> res, int left, int right, String curr) {
        if(left < 0 || right < 0) return;
        if(left == 0 && right == 0) {
            res.add(curr);
            return;
        }
        
        helper(res, left - 1, right, curr + "(");
        if(left < right) {
            helper(res, left, right - 1, curr + ")");
        }
    }
}