- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0022-generate-parentheses.rb
46 lines (37 loc) · 1023 Bytes
/
0022-generate-parentheses.rb
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
# frozen_string_literal: true
# 22. Generate Parentheses
# https://leetcode.com/problems/generate-parentheses
# Medium
=begin
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
* 1 <= n <= 8
=end
# @param {Integer} n
# @return {String[]}
defgenerate_parenthesis(n)
@res=[]
backtrack("",0,0,n)
@res
end
defbacktrack(curr,open,close,n)
@res << currandreturnifcurr.length == n * 2
backtrack(curr + "(",open + 1,close,n)ifopen < n
backtrack(curr + ")",open,close + 1,n)ifclose < open
end
# ********************#
# TEST #
# ********************#
require"test/unit"
classTest_generate_parenthesis < Test::Unit::TestCase
deftest_
assert_equal["((()))","(()())","(())()","()(())","()()()"],generate_parenthesis(3)
assert_equal["()"],generate_parenthesis(1)
end
end