【Leetcode】:22. Generate Parentheses 問題 in Go語言

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.