Leetcode 22 Generate Parentheses Solution in java | Hindi Coding Community

0

 


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

 



class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
recurse(res, 0, 0, "", n);
return res;
}
public void recurse(List<String> res, int left, int right, String s, int n) {
if (s.length() == n * 2) {
res.add(s);
return;
}
if (left < n) {
recurse(res, left + 1, right, s + "(", n);
}
if (right < left) {
recurse(res, left, right + 1, s + ")", n);
}
}
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !