Voyz's Studio.

LeetCode算法笔记--括号生成

字数统计: 133阅读时长: 1 min
2020/11/04 Share

LeetCode算法笔记–Day35

22. Generate Parentheses

题目:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

example
input: n = 3
output: [“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]

My Answer:

方法一:递归

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

7ec04f84e936e95782aba26c4663c5fe7aaf94a2a80986a97d81574467b0c513-LeetCode 第 22 题:“括号生出”题解配图.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let _res = [];
let _str = '';

let dfs = function(_str,left,right){
if(left == 0 && right == 0){
_res.push(_str)
return _res;
}
if(left > right){
return
}
if(left>0){
dfs(_str+'(',left-1,right)
}
if(right>0){
dfs(_str+')',left,right-1)
}
}

dfs(_str,n,n);
return _res;
};

Snip20200804_1.png

CATALOG
  1. 1. LeetCode算法笔记–Day35
  2. 2. 22. Generate Parentheses
    1. 2.1. 题目:
    2. 2.2. My Answer:
      1. 2.2.1. 方法一:递归