在Go(Golang)中生成有效的小括号的方法

261 阅读1分钟

概述

给定一个int n,表示小括号的数量,生成所有有效的、格式良好的小括号。

例如

Input:1
Output: [()]

Input:2
Output: [()(), (())]

Input:2
Output: [()()() ()(()) (())() (()()) ((()))]

程序的想法是使用两个整数

  • open - 代表到目前为止使用的左括号的数量

  • close - 代表到目前为止使用的右小括号的数量。

我们只在以下情况下添加左括号

open < n //where n is the number of pairs of parentheses

只有在以下情况下才添加右括号

close < open //Number of right parentheses is less than the number of left parentheses

下面是同样的程序

package main

import "fmt"

func main() {
	output := generateParenthesis(1)
	fmt.Println(output)

	output = generateParenthesis(2)
	fmt.Println(output)

	output = generateParenthesis(3)
	fmt.Println(output)
}

func generateParenthesis(n int) []string {
	input := ""
	for i := 0; i < n; i++ {
		input = input + "  "
	}
	output := generateParenthesisUtil(0, n, 0, 0, []rune(input))
	return output
}

func generateParenthesisUtil(pos, n, open, close int, input []rune) []string {

	var output []string
	if pos == n*2 {
		output = append(output, string(input))
		return output
	}

	if close < open {
		input[pos] = ')'
		result := generateParenthesisUtil(pos+1, n, open, close+1, input)
		output = append(output, result...)

	}

	if open < n {
		input[pos] = '('
		result := generateParenthesisUtil(pos+1, n, open+1, close, input)
		output = append(output, result...)
	}

	return output
}

输出

[()]
[()() (())]
[()()() ()(()) (())() (()()) ((()))]