10.9 Generate Parentheses

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

http://cs.lmu.edu/~ray/notes/binarytrees/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值