這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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}