與遞歸解決方案試圖this:迴文子遞歸解決方案使用全局變量
遞歸我創建的所有子串,並檢查它是否是迴文與否。
問題是我想擺脫全局變量count。
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def palin(s):
if s == s[::-1]:
return True
return False
global count
count = 0
def helper(s, cur, dp):
global count
ret = 0
if cur >= len(s)-1:
return 0
if cur in dp:
return
for i in range(cur+1, len(s)):
if palin(s[cur:i+1]):
count += 1
ret = helper(s, i, dp)
else:
ret = helper(s, i, dp)
dp[cur] = ret
helper(s, 0, {})
return count + len(s)
我迄今爲止嘗試:
def helper(s, cur, dp, count):
ret = 0
if cur >= len(s)-1:
return count
if cur in dp:
return dp[cur]
for i in range(cur+1, len(s)):
if palin(s[cur:i+1]):
ret = helper(s, i, dp, count + 1)
else:
ret = helper(s, i, dp, count)
dp[cur] = ret
return dp[cur]
FWIW,如果您給出變量的全名或評論它們的含義,這將會很有幫助。例如,'dp'就像是「palidromes字典」的東西吧?考慮把它稱爲「palidromes」或「palidromes_dict」。 – combinatorist