leetcode -- Palindrome Partitioning -- 重点 dfs

https://leetcode.com/problems/palindrome-partitioning/

分割问题,找分割点。这里可以有多个分割点,本质就是选取分割点的子集,能够满足palindrome的条件即可。运用普通的dfs就行

参考http://www.cnblogs.com/zuoyuan/p/3758437.html

class Solution(object):

    def checkPalindrome(self, s):

        if len(s) == 0: return True
        i,j = 0, len(s) - 1
        while i<=j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True

    def dfs(self, candidates, start, end, subres, res):
        if start > end:
            res.append(subres[:])
            return
        else:
            for i in xrange(start, end + 1):#对于start到end的candidates, 其分割点应该是包括i从start到end每个点,candidates[:i+1]即为被分割的部分,包括整个candidates
                if self.checkPalindrome(candidates[start: i + 1]):
                    self.dfs(candidates, i + 1, end, subres + [candidates[start: i + 1]], res)

    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        res = []
        self.dfs(s, 0, len(s)-1,[],res)
        return res

自己复习重写code

class Solution(object):

    def isP(self, s):
        i,j = 0, len(s) - 1
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True

    def dfs(self, s, subres, res):

        if len(s) == 0:
            res.append(subres)
            return
        for i in xrange(len(s)):
            if self.isP(s[:i+1]):
                self.dfs(s[i+1:], subres + [s[:i+1]], res)

    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        if not s: return []
        res = []
        self.dfs(s, [], res)
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值