Leetcode練習(Python):回溯算法類:第131題:分割回文串:給定一個字符串 s,將 s 分割成一些子串,使每個子串都是回文串。 返回 s 所有可能的分割方案。


題目:
分割回文串:給定一個字符串 s,將 s 分割成一些子串,使每個子串都是回文串。  返回 s 所有可能的分割方案。
思路:
使用回溯算法的模板。
程序:
class Solution:
    def partition(self, s: str) -> List[List[str]]:
        if not s:
            return []
        auxiliary = []
        result = []
        def backtrack(s, auxiliary, result):
            if not s:
                result.append(auxiliary[:])
                return
            for index in range(1, len(s) + 1):
                if s[: index] == s[index - 1 : : -1]:
                    auxiliary.append(s[: index])
                    backtrack(s[index :], auxiliary, result)
                    auxiliary.pop()
        backtrack(s, auxiliary, result)
        return result


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM