22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
解题思路:DFS算法
func generateParenthesis(n int) []string {
res := &[]string{}
dfs(n, n, "", res)
return *res
}
func dfs(graph int, index int, path string, paths *[]string) {
if graph+index == 0 {
*paths = append(*paths, path)
return
}
if index < graph {
return
}
if graph > 0 {
dfs(graph-1, index, path+"(", paths)
}
if index > 0 {
dfs(graph, index-1, path+")", paths)
}
}