ID | Title | Difficulty | |
---|---|---|---|
Loading... |
22. Generate Parentheses
Medium
LeetCode
String, Dynamic Programming, Backtracking
Problem
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: ["()"]
Constraints:
- 1 <= n <= 8
Code
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
if(n <= 0) return res;
helper(res, n, n, "");
return res;
}
private void helper(List<String> res, int left, int right, String curr) {
if(left < 0 || right < 0) return;
if(left == 0 && right == 0) {
res.add(curr);
return;
}
helper(res, left - 1, right, curr + "(");
if(left < right) {
helper(res, left, right - 1, curr + ")");
}
}
}
按 <- 键看上一题!
21. Merge Two Sorted Lists
按 -> 键看下一题!
23. Merge k Sorted Lists