Given
n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class GenerateParentheses {public static void main(String[] args) {int n = 3;res = new ArrayList<String>();List<String> paren = generateParenthesis(n);System.out.println(Arrays.asList(paren));}static List<String> res;static List<String> generateParenthesis(int n) {generate("", 0, 0, n);return res;}static void generate(String cur, int open, int close, int max1) {if (cur.length() == max1 * 2) {res.add(cur);return;}// if open is lessif (open < max1)generate(cur + "(", open + 1, close, max1);// if close is lessif (close < open)generate(cur + ")", open, close + 1, max1);}}
C++
#include <bits/stdc++.h>using namespace std;void generate(vector<string> &res,string cur,int open,int close,int max1){if(cur.length()== max1*2){res.push_back(cur);return;}//if open is lessif (open < max1)generate(res, cur+"(", open+1, close, max1);//if close is lessif (close < open)generate(res, cur+")", open, close+1, max1);}vector<string> generateParenthesis(int n){vector<string> res;generate(res,"",0,0,n);return res;}int main(){int n=3;vector<string> paren= generateParenthesis(n);cout<<"[";for(int i=0;i<paren.size()-1;i++)cout<<paren[i]<<",";cout<<paren[paren.size()-1]<<"]";return 0;}
No comments:
Post a Comment