leetcode 22题 括号生成
示例1
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例2
输入:n = 1
输出:["()"]
思路
全排列型问题,可以通过回溯法解答
代码
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
if (n === 0) {
return [];
}
const res = [];
findGrenerateParentthesis(n, n, "", res);
return res;
};
function findGrenerateParentthesis(lindex, rindex, str, res) {
if (lindex === 0 && rindex === 0) {
res.push(str);
return;
}
if (lindex > 0) {
findGrenerateParentthesis(lindex-1, rindex, str + "(", res);
}
if (rindex > 0 && lindex < rindex) {
findGrenerateParentthesis(lindex, rindex-1, str + ")", res);
}
}
复杂度分析:
- 时间复杂度: O(N)
- 空间复杂度:O(N^2)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG