LeetCode-22. Generate Parentheses
2017-02-15 19:42
330 查看
一、问题描述
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
二、解题思路
结构类似于二叉树,树叶即为我们所获得的一个结果,利用递归调用实现该二叉树。但需要注意两点,1左括号的最大个数为n;2.如果右括号的个数小于左括号的个数,则添加右括号,当且仅当左右括号数都为n时将该结果添加到列表中。
三、代码
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
二、解题思路
结构类似于二叉树,树叶即为我们所获得的一个结果,利用递归调用实现该二叉树。但需要注意两点,1左括号的最大个数为n;2.如果右括号的个数小于左括号的个数,则添加右括号,当且仅当左右括号数都为n时将该结果添加到列表中。
三、代码
public class Solution { public List<String> generateParenthesis(int n) { LinkedList<String> result=new LinkedList<String>(); if(n<=0) return result; GP(n,n,result,""); return result; /* result.add("()"); for(int i=1;i<n;i++){ while(result.peek().length()==i*2){ String temp1=result.remove(); result.add("("+temp1+")"); String temp2="()"+temp1; String temp3=temp1+"()"; result.add(temp2); if(!temp2.equals(temp3)){ result.add(temp3); } } } return result; */ } public void GP(int left,int right,List<String> result,String temp){ if(left==0 && right==0){ result.add(temp); return; } if(left>0) GP(left-1,right,result,temp+"("); if(right>left) GP(left,right-1,result,temp+")"); } }
相关文章推荐
- leetcode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses(java)
- LeetCode22. Generate Parentheses
- leetcode_middle_27_22. Generate Parentheses
- leetcode 22. Generate Parentheses
- [LeetCode] 22. Generate Parentheses ☆☆
- leetcode解题之22. Generate Parentheses java 版(圆括号的合法序列)
- 【LeetCode】22. Generate Parentheses
- LeetCode --- 22. Generate Parentheses
- LeetCode - 22. Generate Parentheses
- leetcode: 22. Generate Parentheses
- <LeetCode OJ> 22. Generate Parentheses
- 【Leetcode】:22. Generate Parentheses 问题 in Go语言
- Leetcode 22. Generate Parentheses(python)
- LeetCode-22. Generate Parentheses
- 【C++】【LeetCode】22. Generate Parentheses
- [LeetCode]22. Generate Parentheses
- leetcode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses