python leetcode 131. Palindrome Partitioning
阿新 • • 發佈:2018-12-14
雖然是求所有情況,但用dp也能做,不需要DFS。仔細想想這裡的動態轉移方程會大有收穫。
class Solution:
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
dp = [[] for _ in range(len(s)+1)]
for i in range(1, len(s)+1):
for j in range(i):
if self.isPalindrome(s[j:i]):
if len(dp[j]) > 0:
for l in dp[j]:
dp[i].append(l+[s[j:i]])
else:
dp[i].append([s[j:i]])
return dp[-1]
def isPalindrome (self,s):
for i in range(len(s)>>1):
if s[i] != s[len(s)-1-i]:
return False
return True