classSolution(object): defpartition(self, s): """ :type s: str :rtype: List[List[str]] """ ans = [] path = [] n = len(s)
defdfs(i, start): if i == n: ans.append(path[:]) return if i < n-1: dfs(i+1,start) t = s[start: i+1] if t == t[::-1]: path.append(t) dfs(i+1,i+1) path.pop() dfs(0,0) return ans
动态规划:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defpartition(self, s): """ :type s: str :rtype: List[List[str]] """ dp = [[[]]] # dp[i]表示s[:i]所有可能的分割方案 for i inrange(1, len(s) + 1): dp.append([]) for j inrange(i): tmp = s[j:i] if tmp == tmp[::-1]: dp[-1].extend(l + [tmp] for l in dp[j]) print(dp) return dp[-1]