您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Generate Parentheses

2012-09-06 05:00 302 查看
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:

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

public static List<string> GenerateParenthesesDPOpt(int n)
{
List<HashSet<string>> ret = new List<HashSet<string>>();
ret.Add(new HashSet<string>(){""});

for (int i = 1; i <= n; i++)
{
ret.Add(new HashSet<string>());
foreach (var s in ret[i - 1])
{
string temp = "()" + s;
ret[i].Add(temp);

temp = s + "()";
ret[i].Add(temp);

temp = "(" + s + ")";
ret[i].Add(temp);

for (int j = 0; j < s.Length; j++) //Credit to ffengfrank, Thank you!
{
if (s[j] == '(')
{
temp = s.Insert(j + 1, "()");
ret[i].Add(temp);
}
}
}
}

return ret
.ToList();
}


代码分析:

  DP

n = 1 : ()

n = 2 : ()(), ()()重复, (())

n = 3 : ()()(), ()()()重复, (()()), ()(()), (())(), ((()))

......

利用HASHSET<string>减少时间复杂度。 每次比较的时间从O(n)到O(1)

感谢ffengfrank找到的bug,添加了20 ~ 27代码。

public static List<string> GenerateParenthesesRecursive(int n)
{
string result = "";
List<string> ret = new List<string>();
GenerateParenthesesRecursive(n, n, result, ret);
return ret;
}

public static void GenerateParenthesesRecursive(int left, int right, string result, List<string> ret)
{
if (left == 0 && right == 0)
{
ret.Add(result);
}
else
{
if (left > 0)
{
result += "(";
GenerateParenthesesRecursive(left - 1, right, result, ret);
result = result.Remove(result.Length - 1);
}
if (right > left)
{
result += ")";
GenerateParenthesesRecursive(left, right - 1, result, ret);
result = result.Remove(result.Length - 1);
}
}
}


代码分析:

  递归做法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: