题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
package main /** * * @param n int整型 * @return string字符串一维数组 */ func generateParenthesis(n int) []string { ans := make([]string, 0) var dfs func(pos int, n int, m int, vis []int) dfs = func(pos int, n int, m int, vis []int) { m++ if pos == n-1 { vis[pos] = m arr := make([]byte, 0) for i := 0; i < n; i++ { arr = append(arr, '(') for j := 0; j < vis[i]; j++ { arr = append(arr, ')') } } ans = append(ans, string(arr)) return } for i := 0; i <= m; i++ { vis[pos] = i dfs(pos+1, n, m-i, vis) vis[pos] = 0 } } dfs(0, n, 0, make([]int, n)) return ans // write code here }