-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22.generate-parentheses.cpp
53 lines (40 loc) · 1.13 KB
/
22.generate-parentheses.cpp
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
/*
* @lc app=leetcode id=22 lang=cpp
*
* [22] Generate Parentheses
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
// function signature: string, open parenthesis count, close parenthesis count
stack<pair<string, pair<int, int>>> stk;
stk.push({"", { 0, 0 }});
while(!stk.empty()) {
// function content
string str = stk.top().first;
if(str.size() == n * 2) {
result.push_back(str);
}
pair<int, int> countPair = stk.top().second;
stk.pop();
if(countPair.second < countPair.first) {
stk.push({str + ')', { countPair.first, countPair.second + 1 }});
}
if(countPair.first < n) {
stk.push({str + '(', { countPair.first + 1, countPair.second }});
}
}
return result;
}
};
// @lc code=end