131 Palindrome Partitioning

131 Palindrome Partitioning 

这道题先是标识出所有的 s[i:j+1] 是否为 palindrome, 然后在暴力搜索就好

class Solution:
    def __init__(self):
        self.dp = []
        self.ans = []
    
    def partition(self, s):
        LS = len(s)
        dp = [[False] * LS for i in range(0, LS)]
        for ls in range(0, LS):
            for i in range(0, LS-ls):
                if s[i] == s[i+ls] and (ls <= 2 or dp[i+1][i+ls-1]):
                    dp[i][i+ls] = True
        self.dp = dp[:]
        self.help(0, LS, [], s)
        return self.ans

    def help(self, b, e, tmp, s):
        for i in range(b, e):
            if i < e-1 and self.dp[b][i]:
                tmp.append(s[b:i+1])
                self.help(i+1, e, tmp, s)
                tmp.pop()
            if i == e-1 and self.dp[b][i]:
                self.ans.append(tmp+[s[b:i+1]])
                return

 

posted @ 2015-08-05 00:55  dapanshe  阅读(104)  评论(0编辑  收藏  举报