/**
* Problem: LeetCode 22 - Generate Parentheses
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.ArrayList;
import java.util.List;
/**
* Problem: LeetCode 22 - Generate Parentheses
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
backtrack(result, new StringBuilder(), 0, 0, n);
return result;
}
private void backtrack(List<String> result, StringBuilder sb, int open, int close, int n) {
if (sb.length() == 2 * n) {
result.add(sb.toString());
return;
}
if (open < n) {
sb.append('(');
backtrack(result, sb, open + 1, close, n);
sb.deleteCharAt(sb.length() - 1);
}
if (close < open) {
sb.append(')');
backtrack(result, sb, open, close + 1, n);
sb.deleteCharAt(sb.length() - 1);
}
}
}
"""
Problem: LeetCode 22 - Generate Parentheses
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
def backtrack(current: list, open_count: int, close_count: int):
if len(current) == 2 * n:
result.append("".join(current))
return
if open_count < n:
current.append('(')
backtrack(current, open_count + 1, close_count)
current.pop()
if close_count < open_count:
current.append(')')
backtrack(current, open_count, close_count + 1)
current.pop()
backtrack([], 0, 0)
return result
/**
* Problem: LeetCode 22 - Generate Parentheses
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <string>
using namespace std;
/**
* Problem: LeetCode 22 - Generate Parentheses
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string current = "";
backtrack(result, current, 0, 0, n);
return result;
}
private:
void backtrack(vector<string>& result, string& current, int open, int close, int n) {
if (current.length() == 2 * n) {
result.push_back(current);
return;
}
if (open < n) {
current.push_back('(');
backtrack(result, current, open + 1, close, n);
current.pop_back();
}
if (close < open) {
current.push_back(')');
backtrack(result, current, open, close + 1, n);
current.pop_back();
}
}
};
/**
* Problem: LeetCode 22 - Generate Parentheses
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var generateParenthesis = function(n) {
const result = [];
const backtrack = (current, open, close) => {
if (current.length === 2 * n) {
result.push(current);
return;
}
if (open < n) {
backtrack(current + '(', open + 1, close);
}
if (close < open) {
backtrack(current + ')', open, close + 1);
}
};
backtrack('', 0, 0);
return result;
};