0
点赞
收藏
分享

微信扫一扫

[LeetCode]131. 分割回文串(java实现)dfs爆搜

逸省 2022-03-18 阅读 25

[LeetCode]131. 分割回文串(java实现)dfs爆搜+剪枝

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 读题(需要重点注意的东西)

思路(dfs爆搜+剪枝):

  1. 爆搜:

    • 搜索到最后一个字符,将path加到res中

    • 否则每次从u开始爆搜回文子串,搜索到回文子串[u,i],然后从i+1 的位置 dfs下一个回文子串

  2. 剪枝:判断当前子串[u,i]是否是回文子串

3. 解法

---------------------------------------------------解法---------------------------------------------------

class Solution {
    public List<List<String>> res = new ArrayList<>();
    public List<String> path = new ArrayList<>();

    public List<List<String>> partition(String s) {
        if(s.length() == 0) return res;
        dfs(s,0);
        return res;
    }

    // 爆搜
    public void dfs(String s,int u){
        // 搜索到最后一个字符,将path加到res中
        if(u == s.length()){
            res.add(new ArrayList<>(path));
            return;
        }

        // 每次从u开始爆搜回文子串,然后从i+1的位置dfs下一个回文子串
        for(int i = u;i < s.length(); i++){
            if(check(s.substring(u,i+1))){
                path.add(s.substring(u,i+1));
                dfs(s,i+1);
                path.remove(path.size() - 1);
            }
        }
    }

    // 判断当前区间是不是回文串
    public boolean check(String s){
        int i = 0, j = s.length() - 1;
        while(i < j){
            if(s.charAt(i) != s.charAt(j)) return false;
            i ++;
            j --;
        }
        return true;
    }

}

可能存在的问题:

4. 可能有帮助的前置习题

5. 所用到的数据结构与算法思想

6. 总结

最坏情况下时间复杂度为指数级别O(2n),可以断定是一个爆搜问题

举报

相关推荐

0 条评论