Similar Problems
Similar Problems not available
Valid Arrangement Of Pairs - Leetcode Solution
Companies:
LeetCode: Valid Arrangement Of Pairs Leetcode Solution
Difficulty: Hard
Topics: depth-first-search graph
The Valid Arrangement Of Pairs problem on LeetCode can be solved using the Backtracking algorithm. The problem statement is:
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: ["()"]
To solve this problem, we can use the following approach:
- Initialize an empty list to store all valid combinations of parentheses.
- Create a helper function that takes the following parameters:
- an empty string (current combination)
- an integer representing the current depth of the tree (which is 0 initially)
- an integer representing the maximum depth of the tree (which is 2*n initially)
- an integer representing the number of open parentheses in the current combination (which is 0 initially)
- an integer representing the number of closed parentheses in the current combination (which is 0 initially)
- Inside the helper function, if the current depth is equal to the maximum depth, check if the current combination is valid (i.e. it has equal numbers of open and closed parentheses). If it is valid, append it to the list of valid combinations.
- If the current depth is less than the maximum depth, we have two options:
- Add an open parenthesis to the current combination and call the helper function recursively with the updated parameters (current depth + 1, number of open parentheses + 1, number of closed parentheses).
- Add a closed parenthesis to the current combination only if the number of open parentheses is greater than the number of closed parentheses, then call the helper function recursively with the updated parameters (current depth + 1, number of open parentheses, number of closed parentheses + 1).
- Finally, return the list of valid combinations.
Here is the Python code for the above approach:
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
def backtrack(combination, depth, max_depth, open_p, close_p):
if depth == max_depth:
if open_p == close_p:
result.append(combination)
return
if open_p < max_depth // 2:
backtrack(combination+"(", depth+1, max_depth, open_p+1, close_p)
if close_p < open_p:
backtrack(combination+")", depth+1, max_depth, open_p, close_p+1)
backtrack("", 0, 2*n, 0, 0)
return result
The time complexity of this solution is O(4^n / sqrt(n)) because in the worst case, we can generate up to 4^n / sqrt(n) combinations of parentheses. The space complexity is O(n) because in the worst case, the maximum depth of the backtracking tree is 2*n.
Valid Arrangement Of Pairs Solution Code
1