问题链接:https://oj.leetcode.com/problems/generate-parentheses/
问题描述:Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
问题分析:这一题本质上和电话号码那题一样,是一个图论和状态机的题,从结果来说就是记录从原点开始构图,然后其实可以不计中间状态的返回原点到每一个叶子节点的路径。因为可以不计中间状态的记录,所以这个情况下我个人认为dfs是更好的一种做法,因为这样可以省去不少空间,只需要一个字符数组做缓存即可。
先给出dfs helper的API会比较容易分析:public void dfshelper(List<String> res, int left, int right, int n, char[] buf)
简单来说状态分为以下几种:
1.left == n & right == n。这个时候表示已经到了叶子节点了,可以存储状态了。
2. left < n。此时分为两种状态, left > right or else。 前者的情况可以分两个叉点,就是下一个字符是'('是')'都可以。后者的状态则表示左右匹配已满,再加')'就犯规了,所以这个时候下一个字符节点只能是'('
3. left == n && right < n,此时表示左框已满,只能加右边的框了。
那么给出代码如下:
public List<String> generateParenthesis(int n) {
List<String> res = new LinkedList<String>();
dfshelper(res, 0, 0, n, new char[n * 2]);
return res;
}
public void dfshelper(List<String> res, int left, int right, int n, char[] buf){
if(left == n && right == n)
res.add(new String(buf));
else{
if(left < n){
if(left > right){
buf[left + right] = '(';
dfshelper(res, left + 1, right, n, buf);
buf[left + right] = ')';
dfshelper(res, left, right + 1, n, buf);
}else{
buf[left + right] = '(';
dfshelper(res, left + 1, right, n, buf);
}
}else{
buf[left + right] = ')';
dfshelper(res, left, right + 1, n, buf);
}
}
}
如果在这里用的是bfs,首先queue里要记录的状态并不是很单纯,但是只通过一个char[] buf来记录中间状态是不可能的。所以这里我选择用的是dfs。
Updated 2017-10-28 : 写了一个更加简洁的答案,post记录一下
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new LinkedList<String>();
char[] tempResultRow = new char[n * 2];
this._generateParenthesisHelper(result, 0, 0, n, tempResultRow);
return result;
}
private void _generateParenthesisHelper(List<String> result, int left, int right, int n, char[] tempResultRow) {
if (left == n && right == n) {
if (n != 0)
result.add(new String(tempResultRow));
} else {
if (left > right) {
tempResultRow[left + right] = ')';
this._generateParenthesisHelper(result, left, right + 1, n, tempResultRow);
}
if (left < n) {
tempResultRow[left + right] = '(';
this._generateParenthesisHelper(result, left + 1, right, n, tempResultRow);
}
}
}
}