forked from timoncui/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerate_Parentheses.cpp
More file actions
42 lines (36 loc) · 1.08 KB
/
Generate_Parentheses.cpp
File metadata and controls
42 lines (36 loc) · 1.08 KB
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
/*
Author: Timon Cui, [email protected]
Title: Generate Parentheses
Description:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Difficulty rating: Easy
Source:
http://www.leetcode.com/onlinejudge
Notes:
Use DP.
All valid parenthesis is of the form (x)y where x and y are valid parenthesis themselves.
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
if (n == 0) return vector<string>(1, "");
if (n == 1) return vector<string>(1, "()");
if (Cache.count(n)) return Cache[n];
vector<string> result;
for (int i = 0; i < n; ++i) {
vector<string> a = generateParenthesis(i), b = generateParenthesis(n - 1 - i);
for (int j = 0; j < a.size(); ++j) {
for (int k = 0; k < b.size(); ++k) {
result.push_back("(" + a[j] + ")" + b[k]);
}
}
}
Cache[n] = result;
return result;
}
private:
map<int, vector<string> > Cache;
};