看到有人问这道题的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;
}
}
青春就应该这样绽放 游戏测试:三国时期谁是你最好的兄弟!! 你不得不信的星座秘密
网友评论已有0条评论, 我也要评论