leetcode22括号生成

leetcode22 Generate Parentheses

Posted by BY on February 21, 2019

前言

新的一年,好好学习

正文

问题来源

本问题来自leetcode上的22题。

问题描述

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

示例 1:

输入: 3
输出: [
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

分析:

回溯法 代码写的有点丑

func generateParenthesis(n int) []string {
    ret := make([]string,0)
    line := make([]rune,2*n)
    backtrack(&ret, line, n, 0, 0, 0)
    return ret
}

func backtrack(ret *[]string, line []rune, n int, index int, left int, right int) {
    if left > n {
        return
    }
    if 2*n-1 == index {
        line[index] = ')'
        *ret = append(*ret, string(line))
        return
    }
    line[index] = '('
    backtrack(ret, line, n, index+1, left+1, right)
    if left > right {
        line[index] = ')'
        backtrack(ret, line, n, index+1, left, right+1)
    }
}

总结:

勤思考。

结语

不管怎么样好好加油。