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
Get idea from here1 and here2.
DFS is used to solve this problem.
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
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.
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
res = [x[:] for x in [[False,]*len(s)]*len(s)]
refer to my article.
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.
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.