Leetcode: Generate Parentheses

来源:互联网 发布:阿里云地域选择 编辑:程序博客网 时间:2024/05/23 11:51

Problem:

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

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"


Solution:

Main Idea:


Code:

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


0 0
原创粉丝点击