聚合国内IT技术精华文章,分享IT技术精华,帮助IT从业人士成长

Leetcode: Generate Parentheses iterative solution

2013-07-28 04:10 浏览: 1448079 次 我要评论(0 条) 字号:

看到有人问这道题的iterative解法,今天做了一下。我没有用stack,我是用queue来解的。


class Element{
    String str;
    int left;
    int right;
    
    public Element(String s, int l, int r){
        str=s;
        left=l;
        right=r;
    }
}

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> al=new ArrayList<String>();
        
        Queue<Element> q=new LinkedList<Element>();
        q.add(new Element("",0,0));
        while(!q.isEmpty()){
            Element e=q.poll();
            if(e.left==n && e.right==n){
                al.add(e.str);
            }
            else{
                if(e.left<n)
                    q.add(new Element(e.str+"(", e.left+1,e.right));
                
                if(e.left>e.right)
                    q.add(new Element(e.str+")",e.left,e.right+1));
            }
        }
        
        return al;
    } 
}

 青春就应该这样绽放  游戏测试:三国时期谁是你最好的兄弟!!  你不得不信的星座秘密


标签:
知识来源: blog.sina.com.cn/s/blog_b9285de20101oa9t.html
本文链接: Leetcode: Generate Parentheses iterative solution
打印 复制链接

网友评论已有0条评论, 我也要评论

发表评论

*

* (保密)

Ctrl+Enter 快捷回复