Last updated on October 5th, 2024 at 04:25 pm
Here, We see Generate Parentheses LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Backtracking, String
Companies
Google, Uber, Zenefits
Level of Question
Medium
Generate Parentheses LeetCode Solution
Table of Contents
Problem Statement
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: [“()”]
1. Generate Parentheses Leetcode Solution C++
class Solution { public: vector<string> generateParenthesis(int n) { int open = n; int close = n; vector<string> ans; string op = ""; solve(op, open, close, ans); return ans; } void solve(string op, int open, int close, vector<string> &ans){ if(open == 0 && close == 0){ ans.push_back(op); return; } if(open == close){ string op1 = op; op1.push_back('('); solve(op1, open-1, close, ans); } else if(open == 0){ string op1 = op; op1.push_back(')'); solve(op1, open, close-1, ans); } else if(close == 0){ string op1 = op; op1.push_back('('); solve(op1, open-1, close, ans); } else{ string op1 = op; string op2 = op; op1.push_back('('); op2.push_back(')'); solve(op1, open-1, close, ans); solve(op2, open, close-1, ans); } } };
2. Generate Parentheses Leetcode Solution Java
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); } } }
3. Generate Parentheses Solution JavaScript
var generateParenthesis = function(n) { const output = []; const dfs = (str, open, close) => { if (open > close) { return; } if (open === 0 && close === 0) { output.push(str); return; } if (open > 0) { dfs(`${str}(`, open - 1, close); } if (close > 0) { dfs(`${str})`, open, close - 1); } }; dfs('', n, n); return output; };
4. Generate Parentheses Solution Python
class Solution(object): def generateParenthesis(self, n): def dfs(left, right, s): if len(s) == n * 2: res.append(s) return if left < n: dfs(left + 1, right, s + '(') if right < left: dfs(left, right + 1, s + ')') res = [] dfs(0, 0, '') return res