Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: “aab”
Output:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
分析: 递归,类似全排列
class Solution(object):
def isPalindrome(self, s):
if len(s)<=1:
return True
i=0;
while i<len(s)/2:
if s[i]!=s[len(s)-i-1]:
return False
i+=1
return True
def getRes(self, s, v, res, level):
if level==len(s):
temp=[]
for val in v:
temp.append(val)
res.append(temp)
return
#return res
for i in range(level,len(s)):
if self.isPalindrome(s[level:i+1]):
v.append(s[level:i+1])
xx= self.getRes(s,v, res,i+1)
v.pop()
return res
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
if len(s)==0:
return [[]]
elif len(s)==1:
return [[s[0]]]
#return
res=[]
return self.getRes(s,[],res,0)
#return res