题目链接:https://leetcode-cn.com/problems/generate-parentheses/
题目思路:
1、每次以‘()‘为单位进行插入排序,‘(‘选择好位置之后,‘)‘只能选择‘(‘之后的位置
2、剪枝:存储每一步的结果,如果下次再出现同一结果,不再递归
3、本题最好的解法,应该是动态规划(待补充)
递归代码:
unc generateParenthesis(n int) []string { parenthesis := []string{} parenthesisMap := map[string]bool{} startString := "()" orgnizeParenthesis(startString, &parenthesisMap, n-1, &parenthesis) return parenthesis } func orgnizeParenthesis(str string, parenthesisMap *map[string]bool, n int, parenthesis *[]string) { if (*parenthesisMap)[str] { //剪枝 return } else { (*parenthesisMap)[str] = true if n == 0 { //最后结果 (*parenthesis) = append((*parenthesis), str) return } } for i := 0; i <= len(str); i++ { tempStr1 := str[0:i] + "(" + str[i:] for j := i + 1; j <= len(tempStr1); j++ { tempStr2 := tempStr1[0:j] + ")" + tempStr1[j:] orgnizeParenthesis(tempStr2, parenthesisMap, n-1, parenthesis) } } }
原文:https://www.cnblogs.com/ybf-yyj/p/12672970.html