013_括号生成

知识点:回溯算法、括号组合判断

LeetCode第二十二题:https://leetcode-cn.com/problems/generate-parentheses/submissions/

语言:GoLang

// 回溯
func generateParenthesis(n int) []string {
    result := []string{}
    backtrack(2 * n, 0, []rune{}, &result)
    return result
}


func backtrack(n int, right int, track []rune, result *[]string) {
    if right < 0 {
        return
    }

    if n == 0 {
        if right == 0 {
            *result = append(*result, string(track))
        }
        return
    }

    track = append(track, '(')
    backtrack(n - 1, right + 1, track, result)
    track = track[:len(track) - 1]

    track = append(track, ')')
    backtrack(n - 1, right - 1, track, result)
    track = track[:len(track) - 1]
}
posted @ 2020-03-08 20:28  Cenyol  阅读(66)  评论(0)    收藏  举报