LeetCode Algorithms 22. Generate Parentheses
来源:互联网 发布:管家婆药品软件 编辑:程序博客网 时间:2024/06/04 19:58
题目难度: Medium
原题描述:
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
题目大意:
让你输出n对匹配的小括号的所有可能组合,当n等于3时,例子如上所示。
解题思路:
一开始看着样例,想到的是假设答案为f(n),则f(n)可以表示为'(' + f(n-1) + ')'和f(i) + f(n-i),i>=1且i<=n-1的所有字符串的合并,但是这样会有重复的字符串,所以想到用一个HashSet保证字符串的唯一性。后来还发现如果使用递归会有重复调用,所以要保存起来计算过的结果,当下一次要使用时立即返回。按着这样的思路就写成了第一份代码,但是并不简洁优美。
第二份代码是参考网上别人的做法,原来还可以直接dfs来做,过程和思路都是很直接的,确实是一个很好的解法。具体做法就是在dfs的过程中统计左括号和右括号出现的次数,先生成左括号,再生成右括号,在生成的过程中要保证左右括号的数量都小于n,并且右括号的数量要小于或等于左括号的数量。
时间复杂度分析:
时间复杂度好像比较复杂?
以下是代码:
代码一:
public class Solution { private Set<String> existedString = new HashSet<String>(); private Map<Integer, List<String>> m = new HashMap<Integer, List<String>>(); public List<String> generateParenthesis(int n) { if(n==1){ return Arrays.asList("()"); } List<String> ans = new ArrayList<String>(); List<String> t1, t2, t3; if(m.containsKey(n-1)){ t1 = m.get(n-1); } else{ t1 = generateParenthesis(n-1); m.put(n-1, t1); } for(String s : t1){ if(existedString.add("(" + s + ")")){ ans.add("(" + s + ")"); } } for(int i=n-1 ; i>=1 ; --i){ if(m.containsKey(i)){ t2 = m.get(i); } else{ t2 = generateParenthesis(i); m.put(i, t2); } if(m.containsKey(n-i)){ t3 = m.get(n-i); } else{ t3 = generateParenthesis(n-i); m.put(n-i, t3); } for(String s1 : t2){ for(String s2 : t3){ if(existedString.add(s1+s2)){ ans.add(s1+s2); } } } } return ans; }}
代码二:
public class Solution { private List<String> ans = new ArrayList<String>(); public List<String> generateParenthesis(int n){ dfs("", 0, 0, n); return ans; } private void dfs(String s , int leftCnt , int rightCnt , int n){ if(leftCnt==n && rightCnt==n){ ans.add(s); } if(leftCnt<n){ dfs(s+"(", leftCnt+1, rightCnt, n); } if(rightCnt<n && rightCnt<leftCnt){ dfs(s+")", leftCnt, rightCnt+1, n); } }}
0 0
- LeetCode-algorithms 22. Generate Parentheses
- LeetCode Algorithms 22. Generate Parentheses
- Algorithms—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
- [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
- JqueryMiniUi
- 随记
- 理解C++中的头文件和源文件的作用
- OpenGL应用——实现DDA算法
- C++第四次作业报告
- LeetCode Algorithms 22. Generate Parentheses
- c++作业四
- 群控系统怎样安装,源码二次开发
- 1!+2!+.......+n!(c代码)
- gem install bundler
- 百度地图中绘制多个点例子
- mysql大数据查询优化30条经验
- Python random 模块小记
- RxJava使用场景小结