zoukankan      html  css  js  c++  java
  • leetcode-131 分割回文串(Palindrome Partitioning)

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

    回文串 是正着读和反着读都一样的字符串。

    示例 1:

    输入:s = "aab"
    输出:[["a","a","b"],["aa","b"]]
    示例 2:

    输入:s = "a"
    输出:[["a"]]
     

    提示:

    1 <= s.length <= 16
    s 仅由小写英文字母组成

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/palindrome-partitioning
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题解:

    DP(动态规划)+ dfs(深度优先搜索)

    创建flag二维数组,记录s[i:j+1]是否为回文字符串。

    计算方法(DP):

      遍历i-j间隔,从1开始,到l-1

      如果s[i:j+1]是回文的话,需要满足两个条件,s[i+1:j]是回文串,并且s[i]等于s[j+1]。

    深度优先搜索(DFS):

      从第一个字符串开始搜索,找以它开头的回文串

      找到一个回文串s[i:j+1]的话,将回文串保存在队列中,接着从下标j+1开始搜索

      搜索结束,就得到了一组可行方案

      回溯,尝试其它的可行方案

    class Solution(object):
    
        def partition(self, s):
            """
            :type s: str
            :rtype: List[List[str]]
            """
            l = len(s)
            flag = [ [True] * l for i in range(l)]
            result = list()
            tmplist = list()
            def init():
                for i in range(1,l):
                    for j in range(l-i):
                        print(i,j,flag[j+1][j+i-1])
                        flag[j][j+i] = flag[j+1][j+i-1] and s[j] == s[j+i]
                # for i in range(l-1,0,-1):
                #     for j in range(i-1,-1,-1):
                #         print(i,j,)
                #         flag[j][i] = flag[j+1][i-1] and s[i] == s[j]
            def dfs(index):
                if (index == l):
                    result.append(tmplist[:])
                    return
                for i in range(index,l):
                    if (flag[index][i]):
                        tmplist.append(s[index:i+1])
                        dfs(i+1)
                        tmplist.pop()
            init()
            #print(flag)
            dfs(0)
            return result
    
    #print(Solution.partition(Solution,'aab'))
    作者:红雨
    出处:https://www.cnblogs.com/52why
    微信公众号: 红雨python
  • 相关阅读:
    eclipse FilteredTree
    Windows API高精度计时 C#版
    循环中响应消息,避免循环时UI线程被阻塞
    Linux rpm 包制作 使用 rpmbuild
    利用Windows API实现精确计时
    C++显示选择文件夹对话框
    android AsyncTask
    [转]Android 动画学习笔记
    eclipse 中导入android 工程时出错:The method of type must override a superclass method 解决方式
    Android 自定义对话框
  • 原文地址:https://www.cnblogs.com/52why/p/14496699.html
Copyright © 2011-2022 走看看