-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathGenerateParentheses.cs
58 lines (54 loc) · 2.91 KB
/
GenerateParentheses.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Source : https://leetcode.com/problems/generate-parentheses/
// Author : codeyu
// Date : 2016年10月10日 20:11:48
/***************************************************************************************
*
*
* 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:
*
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
namespace Algorithms
{
public class Solution022
{
public static IList<string> GenerateParenthesis(int n)
{
List<string> result = new List<string>();
if(n <= 0) return result;
GenerateParenthesis(n,n,"",result);
return result;
}
private static void GenerateParenthesis(int left, int right, string item, List<string> result)
{
if(right < left) return;
if(left==0 && right==0)
{
result.Add(item);
}
if(left > 0)
{
GenerateParenthesis(left-1,right,item+"(",result);
}
if(right > 0)
{
GenerateParenthesis(left,right-1,item+")",result);
}
}
}
}