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

本文介绍了一个中等难度的算法问题——回文划分。通过递归深度优先搜索(DFS)的方法找到字符串的所有可能划分,使得每个子串都是回文串。提供了一个Python实现方案,并附带详细代码解释。

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什么值

转载于:https://www.cnblogs.com/siriusli/p/10392217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值