forked from sshpark/LeetCode-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
22.generate-parentheses.kt
54 lines (51 loc) · 1.1 KB
/
22.generate-parentheses.kt
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* @lc app=leetcode id=22 lang=kotlin
*
* [22] Generate Parentheses
*
* https://leetcode.com/problems/generate-parentheses/description/
*
* algorithms
* Medium (56.51%)
* Likes: 3396
* Dislikes: 202
* Total Accepted: 401.8K
* Total Submissions: 700.3K
* Testcase Example: '3'
*
*
* 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:
*
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*
*/
// @lc code=start
class Solution {
fun generateParenthesis(n: Int): List<String> {
var res = mutableListOf<String>()
dfs(n, n, "", res)
return res
}
private fun dfs(left: Int, right: Int, str: String, res: MutableList<String>) {
if (left > right) return ;
if (left == 0 && right == 0) {
res.add(str);
} else {
if (left > 0) dfs(left-1, right, str+'(', res);
if (right > 0) dfs(left, right-1, str+')', res);
}
}
}
// @lc code=end