zoukankan      html  css  js  c++  java
  • 131. 分割回文串-回溯算法 (leetcode)

    给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

    返回 s 所有可能的分割方案。

    代码:

    class Solution:
        def __init__(self):
            self.res = []

        def partition(self, s: str) -> List[List[str]]:
            
            self.helper(s,[])
            return self.res

        def helper(self,part_of_s,answerList):
            if not part_of_s:
                self.res.append(answerList)
            for i in range(1,len(part_of_s)+1):
                if part_of_s[:i] == part_of_s[:i][::-1]:
                    self.helper(part_of_s[i:],answerList + [part_of_s[:i]])

     思考:

      1. 回溯算法重要的就是回溯,回溯就是把上一步的操作抹去

        a) 在79题单词搜索里体现为:  visited[ i ][ j ] = True;  visted[ i ][ j ] = False

        b)在本题里体现为递归时的变量传递: 不改变当前的anserList 直接传递到下一步 answerList + [part_of_s[:i]],这样循环运行完了以后,answer在本步骤还是没有改变,也不需要抹去上一步操作。

  • 相关阅读:
    python 函数和函数名的应用
    Python 文件操作
    django报错信息解决方法
    小数据池、代码块以及深浅拷贝
    python 字典的增删改查
    ps 整理通道
    unity 捏脸相关
    Unity3D Blend Shape简析
    unity 乳摇
    爱丽丝的头发是怎么制作的
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12444244.html
Copyright © 2011-2022 走看看