LeetCode 22. Generate Parentheses
2021-02-13 13:52:32 # leetcode # core problems # medium

Problem

LeetCode 22. Generate Parentheses

1. 题目简述

给出一个数字n,找出所有可能的括号排列形式。

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:

Input: n = 1
Output: ["()"]

2. 算法思路

相关问题:

  1. LeetCode 52. N-Queens II

极其经典的”八皇后问题“,用回溯法。跟数独问题基本上是一样的,但是要稍微简单些。

回溯法

典型的回溯法,终结条件为左括号少于右括号或者括号数量多余给定数字n。代码如下,这里需要注意的是删除最后一个字符的写法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public List<String> generateParenthesis(int n) {
StringBuilder sb = new StringBuilder("");
List<String> res = new ArrayList<>();

backtrack(sb, res, 0, 0, n);

return res;
}

private void backtrack(StringBuilder sb, List<String> res, int left, int right, int n) {
if (right > left || left > n || right > n) {
return;
}

if (right == n && left == n) {
res.add(sb.toString());
}

// add a left parenthesis
sb.append("(");
backtrack(sb, res, left + 1, right, n);
sb.setLength(sb.length() - 1);

// add a right parenthesis
sb.append(")");
backtrack(sb, res, left, right + 1, n);
sb.setLength(sb.length() - 1);
}
}