您的位置:首页 > 其它

LeetCode Generate Parentheses

2015-09-21 07:15 381 查看
原题链接在这里:https://leetcode.com/problems/generate-parentheses/

采用递归调用helper, left, right, 代表还需要加几个左括号和几个右括号。起始赋值都为n, e.g. 若n=3, 就说明一共需要加三个左括号和三个右括号。

递归函数helper终止条件有两个,一个left>right, 说明")"已经比"("加多了,不合法,另一个终止条件是left==0 && right==0说明都加完了。

否则先加左括号,再加右括号。

Time Complexity: exponential. Space: O(n) 一共用了O(n)层stack.

Unique Binary Search Trees II类似。

AC Java:

public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
if(n <= 0){
return res;
}
String str = new String();
helper(n, n, str, res);
return res;
}
private void helper(int left, int right, String str, List<String> res){
if(left > right){
//if left > right, it means remaining "(" is more than remaining ")"
//This means already added more ")" than "(", which is illegal.
return;
}
if(left == 0 && right == 0){
res.add(str);
return;
}
if(left > 0){
helper(left-1, right, str+"(", res);
}
if(right > 0){
helper(left, right-1, str+")", res);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: