您的位置:首页 > 其它

Leetcode 22 Generate Parentheses

2017-08-17 17:47 387 查看

题目来源:leetcode

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

思想:来自http://blog.csdn.net/uknowfigo/article/details/44095097

想到了回溯,写不出dfs,尴尬如图:



代码

/**
* 递归
* Created by a819 on 2017/8/17.
*/
import java.util.*;
public class GenerateParenthese {
public List<String> generateParenthesis(int n) {
List<String> result=new LinkedList<>();
if (n==0)
return result;
dfs(result,"",n,n);
return result;

}
public void dfs(List<String> result,String s,int left,int right){
if (left>right||left<0||right<0)
return;
if (left==0&&right==0)
result.add(s);

4000
dfs(result,s+"(",left-1,right);
dfs(result,s+")",left,right-1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 字符串