【算法三十六】131. 分割回文串

131. 分割回文串

回溯:

java 复制代码
class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> ans = new ArrayList<>();
        List<String> path = new ArrayList<>();
        backtrack(s,ans,path,0);
        return ans;
    }

    //回溯:
    //终止条件
    //非终止条件:
    //子问题 当前操作(要做什么) 下一个子问题是什么 恢复现场 
    private void backtrack(String s,List<List<String>> ans,List<String> path,int l){
        if(l==s.length()){
            //一定要复制,因为path是一块可以反复擦用的黑板,不然最后就是空的
            ans.add(new ArrayList<>(path));
            return;
        }
        for(int r=l;r<s.length();r++){
            if(palindrome(s,l,r)){
                path.add(s.substring(l,r+1));
                backtrack(s,ans,path,r+1);
                path.remove(path.size() - 1);
            }
        }
    }

    private boolean palindrome(String s,int l,int r){
        while(l<r){
            if(s.charAt(l)!=s.charAt(r)){
                return false;
            }
            l++;
            r--;
        }
        return true;
    }
}

时间复杂度:O(N*2^N) N是字符串长度

空间复杂度:O(N)

相关推荐
有点。3 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
周末也要写八哥4 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸4 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp4 小时前
KV Cache 解析
java·算法
liliangcsdn5 小时前
IVOL与偏度因子的对比测量分析
算法
threerocks6 小时前
Jev 入门第一课
算法
西柚研究生1234567 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338378 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳9 小时前
2026.9.17
数据结构·算法·leetcode
木井巳9 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法