LeetCode 131 分割回文串

2021-09-27 03:22:18 字數 738 閱讀 8099

給定乙個字串 s,將 s 分割成一些子串,使每個子串都是回文串。

返回 s 所有可能的分割方案。

示例:輸入: "aab"

輸出:[

["aa","b"],

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

]思路:回溯法 注意回溯的位置

class solution(object):

def partition(self, s):

""":type s: str

:rtype: list[list[str]]

"""def help(s):

'''判斷s是否回文串

'''i,j=0,len(s)-1

while i<=j:

if s[i]!=s[j]:

return false

else:

i+=1

j-=1

return true

def dfs(temp,s,start):

if start==len(s):

return

for i in range(start,len(s)):

if help(s[start:i+1]):

dfs(temp,s,i+1)

# 回溯

temp.pop()

res=

dfs(,s,0)

return res

Leetcode131 分割回文串

給定乙個字串 s,將 s 分割成一些子串,使每個子串都是回文串。返回 s 所有可能的分割方案。示例 輸入 aab 輸出 aa b a a b public list partition string s partition s,0 new arraylist res return res index...

LeetCode 131 分割回文串

返回 s 所有可能的分割方案。分析 首先要用動態規劃來標記出回文子串的位置,dp i j true表示字串i到j是回文。因此動態規劃判斷時候是用的 dp i j s i s j len 3 dp i 1 j 1 表示當len 3時候只需要判斷兩個端點,其他時候還要判斷中間是否是回文子串。然後使用回溯...

leetcode 131 分割回文串

題目 思路 回溯,寫乙個輔助函式來實現回溯操作。以python 為例,如果當前i length,就代表已遍歷完字串s,將子路徑path加入最終res中。i記錄了每次回溯的開始index。python版 def partition self,s res length len s def helper ...