LeetCode. !!!131. Palindrome Partitioning

该文章介绍了一种解决回文划分问题的算法,通过枚举划分位置并使用动态规划判断子串是否为回文,以递归方式处理子问题。代码示例中展示了如何用Java实现这一算法,包括关键的dp表格计算和深度优先遍历。
摘要由CSDN通过智能技术生成

参考资料:左程云算法课

  1. Palindrome Partitioning
    Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Example 1:

Input: s = “aab”
Output: [[“a”,“a”,“b”],[“aa”,“b”]]

思路:
枚举第一个划分位置,如”abc“。其第一个划分位置end所有可能的结果是 “a”, “ab”, “abd”;然后判断是否回文,如果是,那么调用子递归,解决end+1到len-1上的划分问题。
其中,判断str[l…r]是否是回文,可以用动态规划的方法提前计算好放进dp表,作为递归函数的参数,让递归函数带着跑,需要查的时候就查一下。

public List<List<String>> partition(String s) {
        List<List<String>> ans=new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();

        boolean[][] dp = getdp(s.toCharArray());
        // dp[i][j] means whether or not s[i..j] is parlindrome

        process(s,0,dp,path,ans);
        return ans;
    }
    public void process(String s, int index, boolean[][] dp, LinkedList<String> path, List<List<String>> ans)
    {
        if(index==s.length())
        {
            ans.add(copy(path));
            return;
        }

        // index...end
        for(int end=index;end<s.length();end++)
        {
            if(dp[index][end]) // [index..end] is parlindrome
            {
                path.addLast(s.substring(index,end+1));
                process(s,end+1,dp,path,ans);
                path.pollLast();// 深度优先遍历,清理现场
            }
        }
    
    }
    public boolean[][] getdp(char[] str)
    {
        int n = str.length;
        boolean[][] dp = new boolean[n][n];

        for(int i=0;i<n-1;i++)
        {
            dp[i][i] = true;
            dp[i][i+1]=str[i]==str[i+1];
        }
        dp[n-1][n-1]=true;

        // i=n-3 , n-4, ...0
        // dp[i][j] = [i][j]&&dp[i+1][j-1]
        for(int i=n-3;i>=0;i--)
        {
            for(int j=i+2;j<n;j++)
            {
                dp[i][j] = str[i]==str[j] && dp[i+1][j-1];
            }
        }
        return dp;
    }
    public List<String> copy(LinkedList<String> path)
    {
        List<String> ans = new ArrayList<>();
        for(String s:path)
        {
            ans.add(s);
        }
        return ans;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值