欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode从零单排】No22.Generate Parentheses

发布时间:2025/4/5 编程问答 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【LeetCode从零单排】No22.Generate Parentheses 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

代码

For 2, it should place one "()" and add another one insert it but none tail it,

'(' f(1) ')' f(0)

or add none insert it but tail it by another one,

'(' f(0) ')' f(1)

Thus for n, we can insert f(i) and tail f(j) and i+j=n-1,

'(' f(i) ')' f(j)

public List<String> generateParenthesis(int n) {List<String> result = new ArrayList<String>();if (n == 0) {result.add("");} else {for (int i = n - 1; i >= 0; i--) {List<String> insertSub = generateParenthesis(i);List<String> tailSub = generateParenthesis(n - 1 - i);for (String insert : insertSub) {for (String tail : tailSub) {result.add("(" + insert + ")" + tail);}}}}return result; }

/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/




总结

以上是生活随笔为你收集整理的【LeetCode从零单排】No22.Generate Parentheses的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。