Likou brushing notes: 131. Split palindrome (retrospecting classic questions, directly set the template)

topic:

131, split palindrome string

Given a string s, split s into some substrings so that each substring is a palindrome.

Return all possible splitting schemes for s.

Example:

Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

Problem solution ideas:

Seeing that the title requires "all possible results" instead of "the number of results", under normal circumstances, we know that we need to brute force to search for all feasible solutions, and we can use the "backtracking method". Set the backtracking method python template code directly.

Backtracking method python template routine: https://blog.csdn.net/weixin_44414948/article/details/114489545

Time complexity: O(N * 2 ^ N), because there are a total of O(2^N) segmentation methods, and each segmentation must determine whether the palindrome requires O(N) time complexity.
Space complexity: O(2 ^ N), the returned result can be divided into O(2 ^ N) methods at most.

Problem solution python code:

The Python solution uses a new array path + [s[:i]] each time it searches for the location area. This has the advantage of convenience: different paths use different paths, so path.pop( ) Operation; and there is no need to copy path deeply when res.append(path).

class Solution(object):
    def partition(self, s):
        self.isPalindrome = lambda s : s == s[::-1]
        res = []
        self.backtrack(s, res, [])
        return res
        
    def backtrack(self, s, res, path):
        if not s:
            res.append(path)
            return
        for i in range(1, len(s) + 1): #注意起始和结束位置
            if self.isPalindrome(s[:i]):
                self.backtrack(s[i:], res, path + [s[:i]])

Author: fuxuemingzhu
link: https://leetcode-cn.com/problems/palindrome-partitioning/solution/hui-su-fa-si-lu-yu-mo-ban-by-fuxuemingzh-azhz/
Source: stay button ( LeetCode) https://leetcode-cn.com/problems/palindrome-partitioning/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114490837