【java】131. 分割回文串---学会回溯算法!!!

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

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

示例:

输入: “aab”
输出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

代码:
int[][] dp;

    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        if (null == s || s.length() == 0) {
            return res;
        }
        int length = s.length();
        /*
        它是一个二维矩阵,有三种状态值:
        0表示之前还没有计算过
        1表示从下表i到j的子串是回文串
        2表示不是回文串
        我们只用到了数组的右上半部分
        当然这里也可以使用char数组,空间复杂度更低
         */
        dp = new int[length][length];
        //初始化,单个字符的肯定是回文串
        for (int i = 0; i < length; i++) {
            dp[i][i] = 1;
        }

        ArrayList<String> templist = new ArrayList<>();
        helper(res, templist, s, length, 0);
        return res;
    }

    /**
     * 回溯算法
     *
     * @param res      结果集
     * @param templist 中间list
     * @param s        字符串
     * @param length   字符串长度
     * @param index    从当前位置向后组合判断
     */
    private void helper(List<List<String>> res, ArrayList<String> templist, String s, int length, int index) {
    	//走到这一步就表示走到了最后,添加到结果集
        if (index == length) {
            res.add(new ArrayList<>(templist));//一定要重新new一个对象,templist可以得到重用
        }
        //走到某一步有若干的选择继续走下一步
        for (int i = index; i < length; i++) {
            if (isPalindrome(s, index, i)) {
                templist.add(s.substring(index, i + 1));
                helper(res, templist, s, length, i + 1);
                templist.remove(templist.size() - 1);//回溯算法中回退一定要记得这一步
            }
        }
    }

    //判断是否是回文串,这里首先需要到保存的状态中查看是否之前已经有了,优化时间复杂度
    private boolean isPalindrome(String s, int from, int to) {
        if (dp[from][to] == 1) {
            return true;
        } else if (dp[from][to] == 2) {
            return false;
        } else {
            for (int i = from, j = to; i < j; i++, j--) {
                if (s.charAt(i) != s.charAt(j)) {
                    dp[from][to] = 2;
                    return false;
                }
            }
            dp[from][to] = 1;
            return true;
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惠菁

跪求一键三联

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值