您的位置:首页 > 其它

[Lintcode]Generate Parentheses 生成括号

2016-09-25 17:34 495 查看
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Have you met this question in a real interview? 

Yes

Example

Given 
n = 3
, a solution
set is:
"((()))", "(()())", "(())()",
"()(())", "()()()"


搜索每一种可能的结果,可以使用BFS或者DFS。BFS可是考虑使用队列。但这道题更适合用DFS求解。注意helper函数接收left和right变量,作为左括号和右括号剩余数量。注意当left小于right时,属于异常情况,括号不能完整匹配,所以此时直接返回即可。另外通过变量res储存结果。

public class Solution {
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
public ArrayList<String> generateParenthesis(int n) {
// DFS
ArrayList<String> res = new ArrayList<String>();
helper(n, n, n, "", res);
return res;
}

void helper(int n, int left, int right, String str, ArrayList<String> res) {
if(left > right) return;

if (left == 0 && right == 0) {
res.add(str);
return;
} else if (left == 0 && right != 0) {
while(right-- > 0) str += ")";
res.add(str);
return;
} else if (left != 0 && right == 0) {
return;
} else{
helper(n, left - 1, right, str + "(", res);
helper(n, left, right - 1, str + ")", res);
return;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode