Leetcode** 131. Palindrome Partitioning

Description: Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

A palindrome string is a string that reads the same backward as forward.

Link: 131. Palindrome Partitioning

Examples:

Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]

Example 2:
Input: s = "a"
Output: [["a"]]

思路: 求所有可能的回文切分方式,像之前 博主负雪明烛 在括号生成题目中总结的,求所有解,求所有解中的最优解,大部分是用回溯法,这道题在思考的时候就会发现很像括号生成那个题目,会先看到哪个位置是回文,然后后面的部分又是一个string,就会画出树状的结构去解题。

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        self.res = []
        self.isPalindrome = lambda s : s == s[::-1]
        self.dfs(s, [])
        return self.res
    
    def dfs(self, s, path):
        if not s:
            self.res.append(path)
            return
        for i in range(1, len(s)+1):
            if self.isPalindrome(s[:i]):
                self.dfs(s[i:], path+[s[:i]])

日期: 2021-04-19 今天是周一,要充满活力地过这一周啊

posted @ 2021-04-19 19:22  summer_mimi  阅读(40)  评论(0编辑  收藏  举报