法1:DFS
注意:path 长度是固定的,直接覆盖就行,不需要恢复现场。如果 path 初始化成空列表,就需要恢复现场。
Python
## 最佳写法
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = list()
tmp = ['']*(2*n)
self.dfs(0, 0, 0, tmp, res, n)
return res
def dfs(self, idx, left_count, right_count, tmp, res, n):
if (left_count < right_count or left_count > n or right_count > n):
return
if idx == n * 2:
res.append(''.join(tmp))
return
if left_count > right_count:
tmp[idx] = '('
self.dfs(idx+1, left_count+1, right_count, tmp, res, n)
tmp[idx] = ')'
self.dfs(idx+1, left_count, right_count+1, tmp, res, n)
else:
tmp[idx] = '('
self.dfs(idx+1, left_count+1, right_count, tmp, res, n)
## 写法2
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = list()
tmp = list()
self.dfs(0, 0, 0, tmp, res, n)
return res
def dfs(self, idx, left_count, right_count, tmp, res, n):
if (left_count < right_count or left_count > n or right_count > n):
return
if len(tmp) == n * 2:
res.append(''.join(tmp))
return
if left_count > right_count:
tmp.append('(')
self.dfs(idx+1, left_count+1, right_count, tmp, res, n)
tmp.pop()
tmp.append(')')
self.dfs(idx+1, left_count, right_count+1, tmp, res, n)
tmp.pop() # 回溯, 为了还原现场需要删除!!!
else:
tmp.append('(')
self.dfs(idx+1, left_count+1, right_count, tmp, res, n)
tmp.pop() # 回溯, 为了还原现场需要删除!!!
Java
必须掌握的方法!
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
char[] tmp = new char[n * 2];
dfs(0, 0, 0, tmp, res);
return res;
}
public void dfs(int curIndex, int left, int right, char[] tmp, List<String> res) {
if (left < right || left > tmp.length / 2 || right > tmp.length / 2) {
return;
}
if (curIndex == tmp.length) {
res.add(String.valueOf(tmp));
return;
}
if (left > right) {
tmp[curIndex] = '(';
dfs(curIndex + 1, left + 1, right, tmp, res);
tmp[curIndex] = ')';
dfs(curIndex + 1, left, right + 1, tmp, res);
} else if (left == right) {
tmp[curIndex] = '(';
dfs(curIndex + 1, left + 1, right, tmp, res);
}
}
}