题目描述
https://leetcode-cn.com/problems/score-of-parentheses/
思路题解
https://leetcode-cn.com/problems/score-of-parentheses/solution/gua-hao-de-fen-shu-by-leetcode/
方法1:分治法
class Solution(object):
def scoreOfParentheses(self, S):
def F(i, j):
ans = bal = 0
for k in range(i, j):
print("i=%d,j=%d"%(i,j))
bal += 1 if S[k] == '(' else -1
print("i=%d,k=%d,bal=%d"%(i,k,bal))
if bal == 0:
if k - i == 1:
ans += 1
else:
ans += 2 * F(i+1, k)
i = k+1
return ans
return F(0, len(S))
输入:(())
i=0,j=4
i=0,k=0,bal=1
i=0,j=4
i=0,k=1,bal=2
i=0,j=4
i=0,k=2,bal=1
i=0,j=4
i=0,k=3,bal=0
i=1,j=3
i=1,k=1,bal=1
i=1,j=3
i=1,k=2,bal=0
方法2:栈
class Solution(object):
def scoreOfParentheses(self, S):
stack = [0] #The score of the current frame
for x in S:
if x == '(':
stack.append(0)
else:
v = stack.pop()
stack[-1] += max(2 * v, 1)
return stack.pop()