Skip to content

Instantly share code, notes, and snippets.

@samacs
Created November 23, 2019 19:18
Show Gist options
  • Save samacs/b7ba23406ce5d101d5bfde630a168bd5 to your computer and use it in GitHub Desktop.
Save samacs/b7ba23406ce5d101d5bfde630a168bd5 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"strconv"
)
// Language: Go
//
// Running:
//
// ```go
// $ go run main.go 2
//
// ```
func main() {
args := len(os.Args)
if args == 1 || args > 2 {
fmt.Println("Usage: go run main.go 5")
os.Exit(1)
}
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil {
panic(err)
}
parenthesis := make([]string, 2*n)
balanceParenthesis(parenthesis, 0, int(n), 0, 0)
}
func balanceParenthesis(parenthesis []string, position int, n int, open int, close int) {
if close == n {
for i := 0; i < len(parenthesis); i++ {
fmt.Printf("%s", parenthesis[i])
}
fmt.Println()
return
} else {
if open > close {
parenthesis[position] = "}"
balanceParenthesis(parenthesis, position+1, n, open, close+1)
}
if open < n {
parenthesis[position] = "{"
balanceParenthesis(parenthesis, position+1, n, open+1, close)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment