สมมติว่าเรามีค่า n เราต้องสร้าง parentheses ที่ well-formed ทั้งหมดที่มีวงเล็บเปิดและปิด n คู่ ตัวอย่าง n = 3 ผลลัพธ์คือ ["()()()","()(())","(())()","(()())","((()))"]
ขั้นตอนการทำงาน (Recursive Backtracking)
- กำหนดเมธอด
genParenthesisRec()รับleft, right, temp string, result arrayเริ่มต้น result ว่าง - ฟังก์ชันทำงานดังนี้:
- ถ้า
left = 0 and right = 0ใส่tempลงresultคืนค่า - ถ้า
0: เรียกgenParenthesisRec(left-1, right, temp + "(", result) - ถ้า
right > left: เรียกgenParenthesisRec(left, right-1, temp + ")", result)
- ถ้า
ตัวอย่างโค้ด (Python)
class Solution(object):
def generateParenthesis(self, n):
result = []
self.generateParenthesisUtil(n, n, "", result)
return result
def generateParenthesisUtil(self, left, right, temp, result):
if left == 0 and right == 0:
result.append(temp)
return
if left > 0:
self.generateParenthesisUtil(left-1, right, temp+'(', result)
if right > left:
self.generateParenthesisUtil(left, right-1, temp+')', result)
ob = Solution()
print(ob.generateParenthesis(4))
อินพุต
4
เอาต์พุต
["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]