[Lintcode]136. Palindrome Partitioning /[Leetcode]131. Palindrome Partitioning

136. Palindrome Partitioning / 131. Palindrome Partitioning

  • 本题难度: Medium
  • Topic: Search DFS

Description

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example
Given s = "aab", return:

[
["aa","b"],
["a","a","b"]
]

我的代码

recursion

class Solution:
    """
    @param: s: A string
    @return: A list of lists of string
    """
    def partition(self, s):
        # write your code here
        def dfs(s,part, res):
            if s == '':
                res.append(part)
                return 
            for i in range(1,len(s)+1):
                if isValid(s[:i]):
                    dfs(s[i:],part+[s[:i]],res)
                    
        def isValid(s):
            l = len(s)
            for i in range(l//2):
                if s[i]!=s[l-1-i]:
                    return False
            return True
        res = []
        dfs(s, [], res)
        return res
                
            

思路
非常常见的DFS.
res为全局变量。所以不需要return什么值

posted @ 2019-03-27 02:28  siriusli  阅读(102)  评论(0编辑  收藏  举报