leetcode 131

动态规划 easy, 但是速度好像比较慢

`

class Solution:
def is_palindrome(self, s):
return s[::-1] == s

def partition_2(self, s, index, result_dict):
    tmp = []
    for i in range(0, index + 1):
        if self.is_palindrome(s[i:index+1]):
            # for j in result_dict[i-1]:
            #     tmp.append(j + [s[i:index+1]])
            tmp.extend([j + [s[i:index+1]] for j in result_dict[i-1]])
    result_dict[index] = tmp

def partition(self, s: str) -> List[List[str]]:
    if not s:
        return [[]]
    result_dict = {}
    result_dict[-1] = [[]]
    # if len(s) == 1:
    #     return [[s]]
    # result_dict[0] = [[s]]
    for i in range(0, len(s)):
        self.partition_2(s, i, result_dict)
    return result_dict[len(s) - 1]`
posted @ 2021-08-08 00:25  茫茫碧落  阅读(20)  评论(0编辑  收藏  举报