|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: medium |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - String |
| 7 | + - Dynamic Programming |
| 8 | + - Backtracking |
| 9 | +--- |
| 10 | + |
| 11 | +# [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/description/) |
| 12 | + |
| 13 | +## Description |
| 14 | + |
| 15 | +Given `n` pairs of parentheses, write a function that returns all possible valid combinations of well-formed (i.e., properly opened and closed) parentheses. |
| 16 | + |
| 17 | + |
| 18 | +**Example 1:** |
| 19 | +``` |
| 20 | +Input: n = 2 |
| 21 | +Output: ["(())", "()()"] |
| 22 | +``` |
| 23 | + |
| 24 | +**Example 2:** |
| 25 | +``` |
| 26 | +Input: n = 4 |
| 27 | +Output: ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"] |
| 28 | +``` |
| 29 | + |
| 30 | +**Constraints:** |
| 31 | + |
| 32 | +* `1 <= n <= 8` |
| 33 | + |
| 34 | +## Solution |
| 35 | + |
| 36 | +Require open parentheses before close parentheses. Therefore need to increase number of open parentheses until n at first, then increase number of close parentheses until n. |
| 37 | + |
| 38 | +```java |
| 39 | +class Solution { |
| 40 | + public List<String> generateParenthesis(int n) { |
| 41 | + List<String> result = new ArrayList<>(); |
| 42 | + dfs(result, 0, 0, "", n); |
| 43 | + return result; |
| 44 | + } |
| 45 | + |
| 46 | + public void dfs(List<String> result, int left, int right, String current, int n) { |
| 47 | + if (current.length() == n * 2) { |
| 48 | + result.add(current); |
| 49 | + return; |
| 50 | + } |
| 51 | + if (left < n) { |
| 52 | + dfs(result, left + 1, right, current + "(", n); |
| 53 | + } |
| 54 | + if (right < left) { |
| 55 | + dfs(result, left, right + 1, current + ")", n); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +```python |
| 62 | +class Solution: |
| 63 | + def generateParenthesis(self, n: int) -> list[str]: |
| 64 | + result = [] |
| 65 | + self.dfs(result, 0, 0, "", n) |
| 66 | + return result |
| 67 | + |
| 68 | + def dfs(self, result: list[str], left: int, right: int, current: str, n: int): |
| 69 | + if left == n and right == n: |
| 70 | + result.append(current) |
| 71 | + return |
| 72 | + if left < n: |
| 73 | + self.dfs(result, left + 1, right, current + "(", n) |
| 74 | + if right < left: |
| 75 | + self.dfs(result, left, right + 1, current + ")", n) |
| 76 | +``` |
| 77 | + |
| 78 | +## Complexity |
| 79 | + |
| 80 | +- Time complexity: $$O(2^n)$$ |
| 81 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 82 | + |
| 83 | +- Space complexity: $$O(n)$$ |
| 84 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
0 commit comments