class Solution {
public int scoreOfParentheses(String s) {
return helper(s, 0, s.length()-1);
}
// from l to r (included), the substring is balanced
private int helper(String s, int l, int r){
// when r-l==1, "()"
if(r-l==1) return 1;
int balance = 0;
for(int i = l; i<r; i++){
if(s.charAt(i)=='(') balance++;
if(s.charAt(i)==')') balance--;
if(balance == 0){
return helper(s, l,i) +helper(s, i+1,r);
}
}
// full balanced
return 2*helper(s, l+1, r-1);
}
}