Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

[
  ["aa","b"],
  ["a","a","b"]
]

又是一道回文的题目,回文系列有非常多的题目,主要是DP+search的思路。这题也是。

先用DP求一个是否回文的状态矩阵,之后根据这个状态矩阵做dfs+backtracking;当然也可以一边DP,一边组织结果,针对结尾位置保存一个数组,每次可以针对当前回文字符加上之前那个位置有的所有组合做一个组合(https://discuss.leetcode.com/topic/2884/my-java-dp-only-solution-without-recursion-o-n-2)。

我的代码如下:

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        #first find the 2 dimension dp state
        #then search and backtracking to generate result.
        #dp order is very important
        dp = [[False]*len(s) for i in xrange(len(s))]
        for i in xrange(len(s)-1, -1, -1): #start
            for j in xrange(i, len(s)):    #end
                if s[i] == s[j] and (i+1>j-1 or dp[i+1][j-1] == True): #核心判断语句
                    dp[i][j] = True
        res = []
        self.helper(res, [], 0, dp, s)
        return res
    def helper(self, res, cur, index, dp, s):
        if index == len(s):
            res.append(cur+[])
            return 
        for i in xrange(index, len(s)):
            if dp[index][i] == True:
                cur.append(s[index:i+1])
                self.helper(res, cur, i+1, dp, s)
                cur.pop()
        

 

转载于:https://www.cnblogs.com/sherylwang/p/5837836.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值