Link: https://oj.leetcode.com/problems/generate-parentheses/
My first attempt: the conditions in dfs are wrong!
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
dfs(n, n, "", result);
return result;
}
public void dfs(int l, int r, String tmp, ArrayList<String> result){
if(l == 0 && r == 0){
result.add(tmp);
return;
}
if(l == 0 || r == 0) return;
tmp = tmp + "(";
dfs(l-1, r, tmp+"(", result);
tmp = tmp + ")";
dfs(l, r-1, tmp, result);
}
}
Correct answer:
The conditions should be: (1) If there are still left parentheses (, add (; (2) If there are more right ) than left (, add right).
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
dfs(n, n, "", result);
return result;
}
public void dfs(int l, int r, String tmp, ArrayList<String> result){
if(l == 0 && r == 0){
result.add(tmp);
return;
}
if(l > 0){
dfs(l-1, r, tmp + "(", result);
}
if(l < r){
dfs(l, r-1, tmp + ")", result);
}
}
}
The second condition cannot be changed to : if right ) >0. Otherwise, we will have wrong answer:
Input: n = 1
Ouput: ["()", ")("]
Answer: ["()"]
This is because:
dfs(1, 1, "", res)
If we use
if(r > 0){
dfs(l, r-1, tmp + ")", result);
}
then we allow adding ")" before "(", which is wrong. So
if(l < r){
dfs(l, r-1, tmp + ")", result);
}
just means that we MUST add left before right.
问题:在http://blog.csdn.net/linhuanmars/article/details/19873463, 作者说本题的模型也是卡特兰数。.在
Unique Binary Search Trees
里用过。在那道题里,含义是,一个n个节点的树,可以有i 个左节点,n-1-i个右节点。但是本题里,卡特兰模型的实际含义是什么?@8.29.2014