forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
56 lines (44 loc) · 1.22 KB
/
main2.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
53
54
55
56
/// Source : https://leetcode.com/problems/score-of-parentheses/description/
/// Author : liuyubobobo
/// Time : 2018-06-25
#include <iostream>
#include <stack>
#include <cassert>
using namespace std;
/// Recursive Optimized
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class Solution {
public:
int scoreOfParentheses(string S) {
return score(S, 0, S.size() - 1);
}
private:
int score(const string& s, int l, int r){
int res = 0;
int balance = 0;
int start = l;
for(int i = l ; i <= r ; i ++){
if(s[i] == '(')
balance ++;
else{
balance --;
if(balance == 0){
if(l + 1 == i)
res += 1;
else
res += 2 * score(s, l + 1, i - 1);
l = i + 1;
}
}
}
return res;
}
};
int main() {
cout << Solution().scoreOfParentheses("()") << endl; // 1
cout << Solution().scoreOfParentheses("(())") << endl; // 2
cout << Solution().scoreOfParentheses("()()") << endl; // 2
cout << Solution().scoreOfParentheses("(()(()))") << endl; // 6
return 0;
}