Leetcode131.分割回文串-Palindrome Patitioning-Python-回溯法

解题思路:

1.切割回文串,可以用解决找组合问题的思路解决,而解决组合问题,可以用回溯法,故本题选择回溯法。

2.理解两个事情:1.递归函数里的for循环是横向遍历给定字符串s的每一个字母。2.针对s的每一个字母,比如在切割了第一个字母之后,还有很多种切割方式,这是由不断的调用递归函数来实现的。

3.判断回文串。用双指针法即可。当然此题也可以用动态规划法,但是为了降低难度,我先不采用这个方法,知识点太多吃不消呀。

注意:

1.判断是回文串之后,如何确定s的索引来将回文串添加至path。因为在判断回文串时,传入的函数参数是startIndex,i。这是确认是否是回文串的索引下标,如果是回文串的话,其实索引startIndex不变,只需要将终止索引+1, 即i+1。例如'aab' startIndex==1, i==2,那么待判断的回文串就是ab.假设ab是回文串,那么索引 startIndex, i+1 就代表着aab的ab。So, do you understand?

复制代码
            if self.isPalinDrome(s, startIndex, i):
                self.path.append(s[startIndex:i+1])
            else:
                continue

代码:

复制代码
class Solution(object):
    result = []
    path = []
    
    def traceBacking(self, s, startIndex):
        if startIndex >= len(s):
            self.result.append(self.path[:])
            return
        for i in range(startIndex, len(s)):

            if self.isPalinDrome(s, startIndex, i):
                self.path.append(s[startIndex:i+1])
            else:
                continue
            
            self.traceBacking(s, i+1)
            self.path.pop()
        
    def isPalinDrome(self,s,startIndex, end):
        i = startIndex
        j = end
        while i<j:
            if s[i] != s[j]:
                return False
            i +=1
            j -=1
        return True

    def partition(self, s):
        self.result = []
        self.traceBacking(s, 0)
        return self.result
相关推荐
m0_748252385 分钟前
Ruby 模块(Module)的基本概念
开发语言·python·ruby
子午13 分钟前
【2026原创】水稻植物病害识别系统~Python+深度学习+人工智能+resnet50算法+TensorFlow+图像识别
人工智能·python·深度学习
深蓝电商API16 分钟前
Scrapy ImagesPipeline和FilesPipeline自定义使用
爬虫·python·scrapy
木卫二号Coding19 分钟前
Python-文件拷贝+文件重命名+shutil+记录
开发语言·python
leaves falling19 分钟前
冒泡排序(基础版+通用版)
数据结构·算法·排序算法
老鼠只爱大米24 分钟前
LeetCode算法题详解 56:合并区间
leetcode·并查集·合并区间·区间合并·线性扫描·算法面试
爬山算法38 分钟前
Hibernate(44)Hibernate中的fetch join是什么?
前端·python·hibernate
C雨后彩虹42 分钟前
无向图染色
java·数据结构·算法·华为·面试
一代明君Kevin学长1 小时前
记录一个上手即用的Spring全局返回值&异常处理框架
java·网络·python·spring
坚持就完事了1 小时前
扫描线算法
算法