Leetcode: Palindrome Partitioning

Question

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”]
]
Hide Tags Backtracking
Hide Similar Problems (H) Palindrome Partitioning II (M) Word Break


Solution 1

Analysis

Get idea from here1 and here2.

DFS is used to solve this problem.

Code 1

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """

        res,temp = [],[]
        self.dfs(res, temp, s)
        return res

    def dfs(self, res, temp, s):
        if len(s)==0:
            res.append(temp)
            return 

        for ind in range(len(s)):
            substr = s[0:ind+1]
            if self.isPalindrome(substr):
                self.dfs(res, temp+[substr], s[ind+1:])

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

        return True

Another Similar Code 2


    def dfs(self, res, temp, s):
        if len(s)==0:
            res.append(temp[:])

        for ind in range(len(s)):
            substr = s[0:ind+1]
            if self.isPalindrome(substr):
                temp.append(substr)
                self.dfs(res, temp, s[ind+1:])
                temp.pop()

For code 1, temp+[substr] must be input variable of self.dfs()
For code2, we can put temp.append() and temp.pop() out of self.dfs(), but should use res.append(temp[:]) instead of res.append(temp) in if clause, otherwise res will be empty.

In code 1, each temp in different dfs() will be a new temp (python will create a one with the same value). In code 2, temp is pass-by-reference, all manipulation are made on the same object. One elem will be poped after it is appended, that is why it would be empty.

The reason is in my another article.


Solution 2

using dynamic programming

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """

        res, temp = [], []
        self.T = self.table(s)
        self.helper(res, temp, s,  0)

        return res

    def helper(self, res, temp, s, pos):
        if pos==len(s):
            res.append(temp)

        for ind in range(pos, len(s)):
            if self.T[pos][ind]==True:
                self.helper(res, temp+[s[pos:ind+1]], s, ind+1)

    def table(self,s):
        res = [x[:] for x in [[False,]*len(s)]*len(s)]
        for ind in range(len(s)):
            res[ind][ind] = True

        for ind in range(len(s)):
            l,r = ind-1, ind
            while l>=0 and r<len(s) and s[l]==s[r]:
                res[l][r] = True
                l -= 1
                r += 1
            l,r = ind-1, ind+1
            while l>=0 and r<len(s)  and s[l]==s[r]:
                res[l][r] = True
                l -= 1
                r += 1

        return res

Error

  1. 1.
res = [x[:] for x in [[False,]*len(s)]*len(s)]

refer to my article.


Summary

Actually, these two methods are the same. Method 1 has a small shortcoming that some ranges are calculated repeatedly. It is compensated by method 2 by using dynamic programming, recording the historic result.

Take home message

writing code into different block/functions. It is easy to run that code in our brain. For each function, we should think as many cases as possible to make sure that is right.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值