其他分享
首页 > 其他分享> > leetcode【中等】131、分割回文串

leetcode【中等】131、分割回文串

作者:互联网

在这里插入图片描述
思路:
先用dp[i][j]记录字串是否回文
再dfs回溯

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        length=len(s)
        dp=[[False]*length for _ in range(length)]
        for j in range(length):
            for i in range(j+1):
                if s[i]==s[j]:
                    if j-i<3:dp[i][j]=True
                    else:dp[i][j]=dp[i+1][j-1]
                else:dp[i][j]=False
        
        res=[]
        path=[]

        def dfs(i):
            if i==length:
                res.append(path[:])
                return
            for j in range(i,length):
                if dp[i][j]:
                    path.append(s[i:j+1])
                    dfs(j+1)
                    path.pop()
        dfs(0)
        return res
class Solution {
    public List<List<String>> partition(String s) {
        int len=s.length();
        boolean[][]dp=new boolean[len][len];
        isVaild(s,dp);

        List<List<String>> res = new ArrayList<>();
        dfs(s,dp,0,new ArrayList<>(),res);
        return res;

    }

    public void dfs(String s,boolean[][]dp,int i,ArrayList<String>path,List<List<String>> res){
        if(i==s.length()){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int j=i;j<s.length();j++){
            if(dp[i][j]==true){
                path.add(s.substring(i,j+1));
                dfs(s,dp,j+1,path,res);
                path.remove(path.size()-1);
            }
        }
    }

    public void isVaild(String s,boolean[][]dp){
        int len=s.length();
        for(int j=0;j<len;j++){
            for(int i=0;i<=j;i++){
                if(s.charAt(i)==s.charAt(j)){
                    if(j-i<3) dp[i][j]=true;
                    else dp[i][j]=dp[i+1][j-1];
                }
            }
        }        
    }
}

标签:int,res,List,131,len,length,leetcode,dp,回文
来源: https://blog.csdn.net/qq_40707462/article/details/120773861