【Leetcode】:22. Generate Parentheses 问题 in Go语言
2016-05-02 22:33
513 查看
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:
解题思路:这道题和N-Queen问题非常类似,几乎是一样的解题模式。
首先需要明白,怎么放置括号是合法的,假设n=5的情况,已经合法的放置了4个括号,那么怎么判断下一个放什么括号合法呢?
放左括号:如果之前放置的左括号数>=n,那么一定不合法
放右括号:如果之前放置的左括号数<=之前放置的右括号数,那么一定不合法
func generateParenthesis(n int) []string {
str := make([]string,0)
position := make([]int, n * 2) //第i个小标表示位置i上是左括号还是右括号,0表示左括号1表示右括号
placeParentheses(position, &str, 0, n)
return str
}
func placeParentheses(position []int, str *[]string, i, n int) {
if i == 2 * n { //当所有的括号都放完了
var s string
for _, v := range position {
if v == 0 {
s += "("
} else {
s += ")"
}
}
*str = append(*str, s)
return
}
if isValid(position, i, 0, n) { //放左括号是否合法
position[i] = 0
placeParentheses(position, str, i + 1, n)
}
if isValid(position, i, 1, n) { //放右括号是否合法
position[i] = 1
placeParentheses(position, str, i + 1, n)
}
}
func isValid(position []int, cur int, LR int, n int) bool {
var num_left, num_right int
for i := 0; i < cur; i++ {
if position[i] == 0 {
num_left++
} else {
num_right++
}
}
if LR == 0 { //如果当前放入的是左括号
if num_left >= n {
return false
}
} else { //如果当前放入的是右括号
if num_left <= num_right {
return false
}
}
return true
}
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
解题思路:这道题和N-Queen问题非常类似,几乎是一样的解题模式。
首先需要明白,怎么放置括号是合法的,假设n=5的情况,已经合法的放置了4个括号,那么怎么判断下一个放什么括号合法呢?
放左括号:如果之前放置的左括号数>=n,那么一定不合法
放右括号:如果之前放置的左括号数<=之前放置的右括号数,那么一定不合法
func generateParenthesis(n int) []string {
str := make([]string,0)
position := make([]int, n * 2) //第i个小标表示位置i上是左括号还是右括号,0表示左括号1表示右括号
placeParentheses(position, &str, 0, n)
return str
}
func placeParentheses(position []int, str *[]string, i, n int) {
if i == 2 * n { //当所有的括号都放完了
var s string
for _, v := range position {
if v == 0 {
s += "("
} else {
s += ")"
}
}
*str = append(*str, s)
return
}
if isValid(position, i, 0, n) { //放左括号是否合法
position[i] = 0
placeParentheses(position, str, i + 1, n)
}
if isValid(position, i, 1, n) { //放右括号是否合法
position[i] = 1
placeParentheses(position, str, i + 1, n)
}
}
func isValid(position []int, cur int, LR int, n int) bool {
var num_left, num_right int
for i := 0; i < cur; i++ {
if position[i] == 0 {
num_left++
} else {
num_right++
}
}
if LR == 0 { //如果当前放入的是左括号
if num_left >= n {
return false
}
} else { //如果当前放入的是右括号
if num_left <= num_right {
return false
}
}
return true
}
相关文章推荐
- Go语言入门教程之Arrays、Slices、Maps、Range操作简明总结
- GO语言异常处理机制panic和recover分析
- go语言执行windows下命令行的方法
- Go语言计算两个经度和纬度之间距离的方法
- Go语言排序与接口实例分析
- Go语言导出内容到Excel的方法
- go语言实现sqrt的方法
- Go语言MessageBox用法实例
- Go语言判断指定文件是否存在的方法
- go语言制作的zip压缩程序
- go语言channel实现多核并行化运行的方法
- Go语言MD5加密用法实例
- go语言使用scp的方法实例分析
- Go语言中的switch用法实例分析
- go语言检测文件是否存在的方法
- Go语言里的结构体文法实例分析
- Go语言结构体定义和使用方法
- Go语言的队列和堆栈实现方法
- Go语言实现Fibonacci数列的方法
- go语言里包的用法实例