https://leetcode.com/problems/palindrome-partitioning/

分割问题,找分割点。这里可以有多个分割点,本质就是选取分割点的子集,能够满足palindrome的条件即可。运用普通的dfs就行


class Solution(object):

    def checkPalindrome(self, s):

        if len(s) == 0: return True
        i,j = 0, len(s) - 1
        while i<=j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True

    def dfs(self, candidates, start, end, subres, res):
        if start > end:
            res.append(subres[:])
            return
        else:
            for i in xrange(start, end + 1):#对于start到end的candidates, 其分割点应该是包括i从start到end每个点,candidates[:i+1]即为被分割的部分,包括整个candidates
                if self.checkPalindrome(candidates[start: i + 1]):
                    self.dfs(candidates, i + 1, end, subres + [candidates[start: i + 1]], res)

    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        res = []
        self.dfs(s, 0, len(s)-1,[],res)
        return res

自己复习重写code

class Solution(object):

    def isP(self, s):
        i,j = 0, len(s) - 1
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True

    def dfs(self, s, subres, res):

        if len(s) == 0:
            res.append(subres)
            return
        for i in xrange(len(s)):
            if self.isP(s[:i+1]):
                self.dfs(s[i+1:], subres + [s[:i+1]], res)

    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        if not s: return []
        res = []
        self.dfs(s, [], res)
        return res