22. Generate Parentheses
2016-04-15 19:55
337 查看
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:
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution{ public void solution(List<String> res, String s, int left, int right) { if(left!=0){ solution(res, s + "(", left-1, right); if(left < right) solution(res, s + ")", left, right-1); //left!=0,无脑递归 }else{ while(right!=0){ s = s + ")"; right--; } res.add(s); //这种情况下就是把剩下的")"补上,因为题主不会直接添加指定长度重复的字符串, //所以只能用笨方法。这里优化的话,能打败跟自己同运行时间的,大概60%的人 } return; } public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<String>(); solution(res, "", n, n); return res; } }
相关文章推荐
- Android开发 MeasureSpec介绍
- 1、Hibernate之生成SessionFactory源码追踪
- 观察者模式
- Tell me the area---hdu1798 (数学 几何)
- char[],char *,string之间转换
- 用Jersey为Android客户端开发Restful Web Service
- 计算机程序的思维逻辑 (1) - 数据和变量
- 89. Gray Code
- POJ 3373 Changing Digits
- Leetcode Self Crossing
- 初学android开发--day07
- HDU-1010-Tempter of the Bone(搜索奇偶剪枝)
- 第五次Java作业
- JAVA第五次作业
- python与c互相调用
- 使用Nexus创建Maven私有仓库
- centos6环境创建局域网http方式的yum源
- nefu500(二分,最大流)
- RStudio快捷键
- poj 3233(矩阵快速幂+二分)