22. Generate Parentheses

来源:互联网 发布:hosts网络源 编辑:程序博客网 时间:2024/05/16 15:14

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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

深度优选搜索。

public class Solution {   public List<String> generateParenthesis(int n) {    if(n <= 0)  return null;    ArrayList<String> list = new ArrayList<String>();    String str = new String();    dfs(list,str,n,n);    return list;  }  private void  dfs(ArrayList<String> list, String str, int left, int right){    if(left > right)    return;//problem with ")("    if(left == 0 && right == 0){      list.add(str);    }    if(left > 0)    dfs(list,str+"(",left-1,right);    if(right > 0)   dfs(list, str+")",left,right-1);  }}
0 0
原创粉丝点击