Skip to content

Commit

Permalink
Added code for GenerateParentheses in GoLang (aditya109#545)
Browse files Browse the repository at this point in the history
* Added Soluion of ContainweWithMostWater problem

* Added Example

Signed-off-by: Pranjal Goyal <pranjalgoyal13@gmail.com>

* Added GenerateParentheses code

* Updates

Signed-off-by: Pranjal Goyal <pranjalgoyal13@gmail.com>

* Updated Solution of Sum Of Distance in Tree:

Signed-off-by: Pranjal Goyal <pranjalgoyal13@gmail.com>

* Updated Main method

Signed-off-by: Pranjal Goyal <pranjalgoyal13@gmail.com>

* Added Code for GenerateParen in GoLang

Signed-off-by: Pranjal Goyal <pranjalgoyal13@gmail.com>
  • Loading branch information
pranjalg13 authored and nitishanand99 committed Oct 14, 2021
1 parent c062be8 commit 877d9e5
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Programming/Golang/GenerateParentheses/GenerateParentheses.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

//Steps: 1. Add left paren only when open < n and right paren only when close < open

package main

import "fmt"

func main() {
// Taking Example Input- 1
output := generateParenthesis(3)
fmt.Println(output)

// Taking Example Input-2
output = generateParenthesis(1)
fmt.Println(output)

}

//Priting the pairs
func generateParenthesis(n int) []string {
input := ""
for i := 0; i < n; i++ {
input = input + " "
}
output := generateParenthesisUtil(0, n, 0, 0, []rune(input))
return output
}

//Recursive Function
func generateParenthesisUtil(pos, n, open, close int, input []rune) []string {

var output []string
if pos == n*2 {
output = append(output, string(input))
return output
}

if close < open {
input[pos] = ')'
result := generateParenthesisUtil(pos+1, n, open, close+1, input)
output = append(output, result...)

}

if open < n {
input[pos] = '('
result := generateParenthesisUtil(pos+1, n, open+1, close, input)
output = append(output, result...)
}

return output
}

0 comments on commit 877d9e5

Please sign in to comment.