-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution22.cpp
More file actions
52 lines (47 loc) · 1.19 KB
/
Solution22.cpp
File metadata and controls
52 lines (47 loc) · 1.19 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
43
44
45
46
47
48
49
50
51
52
//
// Solution22.cpp
// Algorithm
//
// Created by Pancf on 2019/12/9.
// Copyright © 2019 Pancf. All rights reserved.
//
#include "Solution22.hpp"
bool isSafe(string& cand, int lindex, int rindex, int n) {
if (lindex > n || rindex > n || rindex > lindex) {
return false;
} else {
return true;
}
}
void bt(vector<string>& rv, string& parentheses, int lindex, int rindex, int n) {
if (!isSafe(parentheses, lindex, rindex, n)) {
return;
}
if (lindex == n && rindex == n) {
rv.push_back(parentheses);
return;
}
parentheses.push_back('(');
if (isSafe(parentheses, lindex + 1, rindex, n)) {
bt(rv, parentheses, lindex + 1, rindex, n);
parentheses.pop_back();
} else {
parentheses.pop_back();
}
parentheses.push_back(')');
if (isSafe(parentheses, lindex, rindex + 1, n)) {
bt(rv, parentheses, lindex, rindex + 1, n);
parentheses.pop_back();
} else {
parentheses.pop_back();
}
}
vector<string> Solution22::generateParenthesis(int n) {
vector<string> rv;
if (n == 0) {
return rv;
}
string cand;
bt(rv, cand, 0, 0, n);
return rv;
}