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;
}
}
第一個方法中使用了回溯
相關文章
- 22. Generate Parentheses (recursion algorithm)Go
- Leetcode - 022. Generate ParenthesesLeetCode
- 【leetcode】22. Generate Parentheses 合法括號串的所有組合LeetCode
- LeetCode Generate Parentheses(022)解法總結LeetCode
- Leetcode 20 Valid ParenthesesLeetCode
- Leetcode 32 Longest Valid ParenthesesLeetCode
- [LeetCode] 32. Longest Valid ParenthesesLeetCode
- LeetCode Valid Parentheses(020)解法總結LeetCode
- Leetcode 20 有效的括號valid-parentheses(棧)LeetCode
- LeetCode 之 JavaScript 解答第20題 —— 有效的括號(Valid Parentheses)LeetCodeJavaScript
- 括號生成-LeetCode22LeetCode
- Longest Valid Parentheses
- 【leetcode】32. Longest Valid Parentheses 最長的有效匹配括號子串長度LeetCode
- 【leetcode】leetcode22括號生成通過程式碼及題解LeetCode
- LeetCode - 22. 括號的生成(遞迴)1LeetCode遞迴
- Q22 LeetCode142 環形連結串列LeetCode
- 09/05 ? LeetCode 熱題 HOT 100 -- 22, 23,31LeetCode
- nuxt-generate 靜態站UX
- Generate BKS File( Bouncy Castle KeyStore)AST
- WPF automatically generate shapes fill wrappanelAPP
- Mybatis-Plus Generate 原始碼分析MyBatis原始碼
- 常識:Verilog語法-generate-for
- C# generate listview and fill data no xamlC#View
- PostgreSQL DBA(99) - Develop(generate random string)SQLdevrandom
- Verilog中genvar 和 generate的使用
- PostgreSQL的generate_series函式應用SQL函式
- 使用 nuxi generate 進行預渲染和部署UX
- Oracle 12.2 How to Generate AWRs in Active Data Guard Standby DatabasesOracleDatabase
- 22
- 22 BFC
- 5/22
- 3/22
- LeetCode題解(Offer22):尋找連結串列中倒數第k個節點(Python)LeetCodePython
- 淺析Vue原始碼(六)—— $mount中template的編譯–generateVue原始碼編譯
- 淺析Vue原始碼(六)—— $mount中template的編譯--generateVue原始碼編譯
- bee工具使用generate/migrate命令都要帶資料庫連線?資料庫
- Generate Distribution Model from SAP ERP to SAP EWM in SAP S/4Hana
- 2018/12/22