LeetCode 22. Generate Parentheses(生成括号)
2016-05-19 07:18
357 查看
原题网址:https://leetcode.com/problems/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:
方法:深度优先搜索。
可以简化:
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 void find(int remain, int left, int right, char[] parenthesis, List<String> results) { if (remain == 0) { results.add(new String(parenthesis)); return; } if (left + 1 <= parenthesis.length/2) { parenthesis[parenthesis.length - remain] = '('; find(remain-1, left+1, right, parenthesis, results); } if (right + 1 <= parenthesis.length/2 && right < left) { parenthesis[parenthesis.length - remain] = ')'; find(remain-1, left, right+1, parenthesis, results); } } public List<String> generateParenthesis(int n) { List<String> results = new ArrayList<>(); find(n*2, 0, 0, new char[n*2], results); return results; } }
可以简化:
public class Solution { private void find(char[] p, int len, int left, int right, List<String> results) { if (len == p.length) { results.add(new String(p)); return; } if (left<p.length/2) { p[len] = '('; find(p, len+1, left+1, right, results); } if (left>right) { p[len] = ')'; find(p, len+1, left, right+1, results); } } public List<String> generateParenthesis(int n) { List<String> results = new ArrayList<>(); find(new char[n*2], 0, 0, 0, results); return results; } }
相关文章推荐
- [leetcode] 191. Number of 1 Bits 解题报告
- 小酌重构系列[16]——引入契约式设计
- 小酌重构系列[16]——引入契约式设计
- linux grep egrep fgrep bash条件判断 bash测试 if 条件判断
- 甲骨文联席 CEO 否认收购 Sun 是为了提起诉讼
- LeetCode 21. Merge Two Sorted Lists(合并链表)
- JVM调优浅谈
- 01.LoT.UI 前后台通用框架分解系列之——小图片背景全屏显示(可自动切换背景)
- pg_prewarm 与 pgfincore的区别
- SDUT 2410 Mine Number 2012年山东省第三届ACM大学生程序设计竞赛题
- 15分钟弄懂 const 和 #define
- 证书相关
- LeetCode 20. Valid Parentheses(括号校验)
- complex类 序列化时 IsRequired = true 问题
- 【华为OJ】【084-求最大连续bit数】
- 编程思想之多线程与多进程(4)——C++中的多线程
- 【华为OJ】【083-计算字符串的相似度】
- 还需要补充很多知识
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- (加精)AndrodStudio 极光推送 推送类手写版加精Demo 续写!!!