leetcode 22. Generate Parentheses
来源:互联网 发布:程序与算法 编辑:程序博客网 时间:2024/06/16 03:39
一个效率极低的版本:bfs 权当作复习了
import java.util.ArrayList;import java.util.List;import java.util.Stack;public class Solution {public static void main(String[] args){Solution s = new Solution();List<String> r = s.generateParenthesis(3);} public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<String>(); String s = ""; char[] cand = {'(',')'}; genThesis("",res,n,cand); return res; } public void genThesis(String prefix,List<String> res,int n,char[] cand){ // bfs if(prefix.length()>2*n) return; if(isAllValid(prefix)&&prefix.length()==2*n){ res.add(prefix); }else{ for(int i=0;i<2;i++){ if(isPartValid(prefix+cand[i])) genThesis(prefix+cand[i],res,n,cand); } } } public boolean isAllValid(String s) { Stack<Character> stack = new Stack<Character>(); for(char c :s.toCharArray()){ if(c=='(') stack.add(')'); // else if(stack.size()==0||stack.pop()!=c) return false; } if(stack.size()>0) return false; return true; } public boolean isPartValid(String s) { Stack<Character> stack = new Stack<Character>(); for(char c :s.toCharArray()){ if(c=='(') stack.add(')'); // else if(stack.size()==0||stack.pop()!=c) return false; } return true; }}
0 0
- [LeetCode]22.Generate Parentheses
- LeetCode --- 22. Generate Parentheses
- LeetCode 22.Generate Parentheses
- [Leetcode] 22. Generate Parentheses
- 【LeetCode】22.Generate Parentheses
- [leetcode] 22.Generate Parentheses
- 【leetcode】22. Generate Parentheses
- Leetcode-22.Generate Parentheses
- [leetcode] 22. Generate Parentheses
- 22. Generate Parentheses LeetCode
- leetcode 22. Generate Parentheses
- [LeetCode]22. Generate Parentheses
- leetcode 22. Generate Parentheses
- leetcode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- [LeetCode]22. Generate Parentheses
- LeetCode *** 22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- 进程检测工具supervisor使用报错(nodemon报错)
- C语言中函数返回字符串的四种方法
- 说说JSON和JSONP,原来ajax引用这个来实现跨域访问的
- 亿科运维平台介绍
- binlog日志中没有insert的记录
- leetcode 22. Generate Parentheses
- 把一个数组分成四份,三个分割点不算进求和中,使得每份的和要相同。
- Python生成器
- simple udp
- bugzilla 系列1安装
- CSS伪类和伪元素
- Spring常用知识点速记
- java中定时器几种实现方式
- To do list