Generate Parentheses
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> result = new ArrayList<>(); // Initialize an empty list to store the results
backtrack(result, "", 0, 0, n); // Start the backtracking process
return result; // Return the list of valid combinations
}
// Helper function for backtracking
private void backtrack(List<String> result, String currentString, int openCount, int closeCount, int max) {
// If the current string length is equal to 2 * n, it means we have used all parentheses
if (currentString.length() == max * 2) {
result.add(currentString); // Add the current valid combination to the result list
return;
}
// If we can still add an open parenthesis, add it and recurse
if (openCount < max) {
backtrack(result, currentString + "(", openCount + 1, closeCount, max);
}
// If we can add a close parenthesis without invalidating the sequence, add it and recurse
if (closeCount < openCount) {
backtrack(result, currentString + ")", openCount, closeCount + 1, max);
}
}
}
Comments
Post a Comment