Leetcode 22 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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
1)
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
backtrack(list,"",0,0,n);
return list;
}
public void backtrack(List<String> list,String cur,int open,int close,int max){
if(cur.length() == max * 2){
list.add(cur);
return;
}
if(open < max){
backtrack(list,cur+"(",open + 1,close,max);
}
if(close < open){
backtrack(list,cur+")",open,close + 1,max);
}
return ;
}
}
2)
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ret = new ArrayList<>();
if (n == 0) {
ret.add("");
} else {
for (int i = 0; i < n; i++) {
for (String left: generateParenthesis(i)) {
for (String right: generateParenthesis(n - i - 1)) {
ret.add("(" + left + ")" + right);
}
}
}
}
return ret;
}
}
第一個方法中使用了回溯
相關文章
- leetcode22_Generate ParenthesesLeetCode
- Leetcode - 022. Generate ParenthesesLeetCode
- Leetcode-Generate ParenthesesLeetCode
- Generate Parentheses leetcode javaLeetCodeJava
- LeetCode Generate Parentheses(022)解法總結LeetCode
- 【LeetCode從零單排】No22.Generate ParenthesesLeetCode
- 22. Generate Parentheses (recursion algorithm)Go
- [LeetCode] Generate Parentheses 生成括號LeetCode
- 【leetcode】22. Generate Parentheses 合法括號串的所有組合LeetCode
- Leetcode Valid ParenthesesLeetCode
- Leetcode 20 Valid ParenthesesLeetCode
- Leetcode-Valid ParenthesesLeetCode
- Valid Parentheses leetcode javaLeetCodeJava
- Leetcode 32 Longest Valid ParenthesesLeetCode
- LeetCode-Remove Invalid ParenthesesLeetCodeREM
- Leetcode-Longest Valid ParenthesesLeetCode
- leetcode 之 Longest Valid ParenthesesLeetCode
- Longest Valid Parentheses leetcode javaLeetCodeJava
- [LeetCode] 32. Longest Valid ParenthesesLeetCode
- leetcode32_Longest Valid ParenthesesLeetCode
- LeetCode-Different Ways to Add ParenthesesLeetCode
- [LeetCode] Valid Parentheses 驗證括號LeetCode
- LeetCode Valid Parentheses(020)解法總結LeetCode
- [LeetCode] Longest Valid Parentheses 最長有效括號LeetCode
- Leetcode 20 有效的括號valid-parentheses(棧)LeetCode
- LeetCode解題報告 241. Different Ways to Add Parentheses [medium]LeetCode
- LeetCode 之 JavaScript 解答第20題 —— 有效的括號(Valid Parentheses)LeetCodeJavaScript
- Remove Invalid Parentheses[難]REM
- plsql generate xml functionSQLXMLFunction
- Leetcode 229 JavaScriptLeetCodeJavaScript
- 演算法Valid Parentheses演算法
- 【leetcode】32. Longest Valid Parentheses 最長的有效匹配括號子串長度LeetCode
- Leetcode-1221LeetCode
- 【Python】 Missing parentheses in call to 'print'Python
- nuxt-generate 靜態站UX
- Use the statspack to generate the accurate explain planAI
- 括號生成-LeetCode22LeetCode
- Mybatis-Plus Generate 原始碼分析MyBatis原始碼