LeetCode Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
很明显这是一道permutation 题,第一想法就是DFS或者BFS,很多人都直接jump to DFS,但其实BFS也是可以的,可能写起来没有DFS更简洁,但是也不为练习和理解BFS的一道好题
太多人贴DFS的解法了,我只贴一下自己的BFS的解法
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
if(n==0) return result;
Queue<Node> q = new LinkedList<Node>();
q.offer(new Node(1,0,"("));
while(q.size()>0){
Node temp = q.poll();
if(temp.left <n){
q.offer(new Node(temp.left+1,temp.right, temp.val +"("));
}
if(temp.right<temp.left && temp.right<n){
q.offer(new Node(temp.left,temp.right+1, temp.val +")"));
}
if(temp.right ==n){
result.add(temp.val);
}
}
return result;
}
class Node{
String val;
int left;
int right;
Node(int left, int right, String val){
this.left = left;
this.right =right;
this.val = val;
}
}
}
另外这道题还有一种Iterative 的解法
public class Solution {
public List<String> generateParenthesis(int n) {
List<List<String>> lists = new ArrayList<>();
lists.add(Collections.singletonList(""));
for (int i = 1; i <= n; ++i)
{
final List<String> list = new ArrayList<>();
for (int j = 0; j < i; ++j)
{
for (final String first : lists.get(j))
{
for (final String second : lists.get(i - 1 - j))
{
list.add("(" + first + ")" + second);
}
}
}
lists.add(list);
}
return lists.get(lists.size() - 1);
}
}

浙公网安备 33010602011771号