Generate Parentheses

July 22, 2025

Question

Given n pairs of parentheses, generate all combinations of well-formed parentheses.

Example

Input: n = 3

Output: ["()()()", "()(())", "(())()", "(()())", "((()))"]

Explanation: All valid combinations of three pairs of balanced parentheses are listed above.

My Notes

package main

import (
    "fmt"
)

type Node struct {
    val string
    o   int
    c   int
}

type Stack struct {
    items []Node
}

func (s *Stack) Push(val string, o int, c int) {
    s.items = append(s.items, Node{val, o, c})
}

func (s *Stack) Pop() Node {
    popped := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return popped
}

func (s *Stack) IsEmpty() bool {
    return len(s.items) == 0
}

func generateParenthesis(n int) []string {
    result := []string{}
    stack := Stack{items: []Node{{val: "", o: 0, c: 0}}}
    
    for !stack.IsEmpty() {
        node := stack.Pop()

        if node.o < n {
            stack.Push(node.val+"(", node.o+1, node.c)
        }

        if node.c < node.o {
            stack.Push(node.val+")", node.o, node.c+1)
        }

        if len(node.val) == 2*n {
            result = append(result, node.val)
        }
    }

    return result
}

func main() {
    result := generateParenthesis(3)
    fmt.Println(result)
}